next js back to previous page
To go back to the previous page in Next.js, you can use the Router
object provided by the next/router
module. The Router
object allows you to programmatically navigate between pages in your Next.js application. Here are the steps to go back to the previous page:
- Import the
Router
object from thenext/router
module at the top of your file:
import { useRouter } from 'next/router';
- Inside your component, you can access the
Router
object using theuseRouter
hook:
const router = useRouter();
- To go back to the previous page, you can use the
back
method of theRouter
object:
router.back();
- Optionally, you can wrap the
router.back()
call inside an event handler or a function to trigger the navigation on a specific action, such as a button click:
const handleGoBack = () => {
router.back();
};
<button onClick={handleGoBack}>Go Back</button>
That's it! When the router.back()
method is called, Next.js will navigate the user back to the previous page in the browser's history.
Remember to import the necessary modules and hooks, and use the useRouter
hook to access the Router
object. Then, you can use the back
method of the Router
object to navigate back to the previous page.