44

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

Danila
  • 9,786
  • 2
  • 22
  • 47
Дмитрий
  • 529
  • 1
  • 5
  • 8
  • You might want to check [Next.js getting started](https://nextjs.org/learn/basics/navigate-between-pages) page. – Tico Aug 14 '18 at 13:58
  • looked but did not find a solution. I tried to do so but get constant page redirects. export const BackUrl = ({url}) => (  

    Nazad

    )
    – Дмитрий Aug 14 '18 at 14:01
  • [Client-Side History Support](https://nextjs.org/learn/basics/navigate-between-pages/client-side-history) states: `When you hit the Back button, it navigates the page to the index page entirely via the client; next/link does all the location.history handling for you.You don't need to write even a single line of client-side routing code.`. So you don't need the `onClick` attribute with `window.history.back()` – Tico Aug 14 '18 at 14:05

1 Answers1

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
  • 1
    It 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
  • Well... I don't think this is very a11y friendly... – Anatole Lucet Nov 20 '20 at 10:21
  • @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