I use routing next.js. How to implement the button back and return to the previous page? Just like with the button on the browser
To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button. Similarly, you can call the navigate function with -2 to go 2 pages back.
To go back to the previous page with React Router v5, we can use the useHistory hook. We have the Foo and Bar components which calls the useHistory hook. In both components, we set the history. goBack method as the value of the onClick prop.
To redirect from / to another page with Next. js, we can get the pathname property from the Router object and do the redirect if pathname is '/' . import React, { useEffect } from "react"; import Router from "next/router"; const Comp = () => { //...
EDIT: 2 years after this answer was first posted, the router method is now well documented. Here is the code straight from the documentation:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return <span onClick={() => router.back()}>Click here to go back</span>
}
ORIGINAL ANSWER:
There is an undocumented Router.back
method (see source) that just does window.history.back()
You should have a component like so
import Router from 'next/router'
export default function BackButton() {
return (
<div onClick={() => Router.back()}>Go Back</div>
)
}
If you are looking to go back using the web browser default back button probably best to look into "window.onpopstate" with something like this -
useEffect(() => {
window.onpopstate = () => {
router.push(/*route logic here*/)
}
})
More details on these page - Want to have an event handler for the browser's back button with next.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With