Home > Software engineering >  Next.js Dynamic Route With a User Inputted URL
Next.js Dynamic Route With a User Inputted URL

Time:10-16

I am using the Next.js Router to enable different dashboards depending on the URL slug. This works when a button with the link is clicked, as the link passes the information to the Next.js Router, but it does not work when a URL is inputted directly into the browser (i.e. it does not work if the user refreshes the page, or just types the URL with the slug directly). So, while I am able to use dynamic routes when links are pressed, how can I enable dynamic routes when a link is not pressed?

The relevant code is below. Thank you very much

const dashboard = () => {
  const router = useRouter();
  const {dashboardID} = router.query;

  return (
    <Dashboard dashboardID = {dashboardID}/>
  );
}

export default dashboard

CodePudding user response:

On pagination the query already loaded on the context.

You need to wait until router fully loads

const dashboard = () => {
      const router = useRouter();
      const {dashboardID} = router.query;
      
      if(!dashboardID) return null //Wait until query with dashboardID loads to avoid undefined errors 
      return (
        <Dashboard dashboardID = {dashboardID}/>
      );
    }
    
    export default dashboard
  • Related