Home > other >  Next.js: how to go to parent page from current child page?
Next.js: how to go to parent page from current child page?

Time:10-10

my apology if this is a super dumb question, I'm a beginner of Next.js and React.js.

I have some basic knowledge that in Next.js, we can create a hierarchy of pages, and the path of a xx_page.js file would be the url route for that js file, as described in the documentation.

For example, my pages are structured as follows,

pages  // a folder
| -- home  // a folder
|     | -- index.js  // a file, the code for route "/home"
      | -- sports  // a folder
      |     | -- index.js  // a file, the code for route "/home/sports"
      |     | -- football.js  // a file, the code for "/home/sports/football"

Suppose the current page is at route "xxx.com/home/sports/football", and on the page there is a "Back" button, after clicking it, we should go back to "xxx.com/home/sports".

I failed to figure out a proper way to do that, mostly what I found by Google are about going back to the previous page, and not what I want.

Please give me some help about how to do it in Next.js, thanks!

CodePudding user response:

There's no correct definition of "Back", so you have to define it. For your button, if you do the following

      <Link href="/home/sports">
        <a className="back"></a>
      </Link>

It should behave exactly what you wanted.

CodePudding user response:

if you are looking to remove the last part of the URL, you can do the below

let a = window.location.href.split("/")
a.pop();
window.location.href = a.join("/");
  • Related