Home > database >  Next.js Router Dynamic URLs and the back button
Next.js Router Dynamic URLs and the back button

Time:08-16

I am using the Router from next/router in order to have a dynamic URL and load different content on the page:

Router.push('/contract', `/contract/${id}`);

The issue is the back button doesn't function as expected afterward.

  1. After the function above runs the 1st click of the back button does not update the URL to the previous URL, but it does load the previous contract content.

  2. The 2nd click of the browser back button does update the URL to the previous page URL, and the page content remains the same (which is now correct relative to the URL)

Extra Note: The main focus here is the browser back button but there is a breadcrumb back button that runs the window.history.back() function that works in this same unexpected manner (which makes sense).

Is the back button a known issue when using the push method of the Router, or dynamic URLs in general? Is there a way to work around that with Javascript?

CodePudding user response:

You can do

import { useRouter } from 'next/router';

export default function YourPage() {

  const router = useRouter();

  return (<div onClick={() => router.back()}>Back</div>);
}

Navigate back in history. Equivalent to clicking the browser’s back button. It executes window.history.back().

Further reading

next/router

CodePudding user response:

Try .slice !

const goBack = () => {
   const { url } = useRouter();
   const prevUrl = url.slice(0, url.lastIndexOf('/'));

   return <a href={prevUrl}> Go Back </a>;
}
  • Related