Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js + React Go back to the previous page

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

like image 345
Дмитрий Avatar asked Aug 14 '18 13:08

Дмитрий


People also ask

How do you route back to previous page in React?

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.

How do I go back in react JS?

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.

How do I redirect a page in Nextjs?

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 = () => { //...


2 Answers

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>
    )
}
like image 188
Clément Prévost Avatar answered Oct 11 '22 07:10

Clément Prévost


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

like image 2
musaa muhsen Avatar answered Oct 11 '22 08:10

musaa muhsen