简体   繁体   中英

Next.js Dynamic Route With a User Inputted URL

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 (ie 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM