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
Asked
Active
Viewed 6.8k times
1 Answers
91
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>
)
}
Clément Prévost
- 6,814
- 1
- 31
- 48
-
1It is worth pointing out, that you may experience odd behaviour on mobile devices if you have `:hover` assigned the element in CSS due to the way onClick is triggered in React on mobile. – Corfitz. Feb 27 '19 at 08:47
-
That just hides the exact same line of code. The link from @Clément is from next 7, v8 did also the same: https://github.com/zeit/next.js/blob/v8.0.4/packages/next-server/lib/router/router.ts#L192 – sja May 02 '19 at 08:57
-
-
@AnatoleLucet very good point, as mentioned, this is the official nextjs example. I know nextjs team likes this kind of feedback, maybe tell them and they will update the documentation. As for this answer, I don't feel like diverging from the official doc to keep things simple – Clément Prévost Nov 21 '20 at 14:16
-
How can we interrupt the web browser's default back button behavior and have it simply run the Router.back() method instead? – Adam Friedman Jan 13 '22 at 21:42
Nazad
) – Дмитрий Aug 14 '18 at 14:01