'NextJs Dynamic Folder Routing

Im trying to achieve a case where you have two seperate navbars, views-nav with links "results", "statistics" and schools-nav with links "school-a", "school-b", "school-c"... The url would look something like this when user first lands:

  https://example.com/results/school-a 

scenario:

  1. Click on .views-nav link[statistics] => https://example.com/statistics/school-a
  2. Then click on .schools-nav link[school-c] => https://example.com/statistics/school-c
  3. Then click on .views-nav link[results] => https://example.com/results/school-c
  4. Then click on .schools-nav link[school-b] => https://example.com/results/school-b
  5. THen click on .views-nav link[statistics] => https://example.com/statistics/school-b

Trying to access https://example.com/statistics/ or https://example.com/results/ manually should redirect to 404.

Expected behavior: clicking on navbar[views] links switches between results and statistics while maintaining the school slug and clicking on navbar[schools] links switches between schools while maintaining views slug.

current folder structure is

       -pages
           |
           -[views]
                 |
                 -[schools].js

./Navbar.jsx

    import { useRouter } from "next/router";

    const Navbar = () => {
    
    const { ??? } = useRouter();

    return (

     <nav>
      <div className="views-nav">
       <Link href=`/results/${???}`>
        results
       </Link>
       <Link href=`/statistics/${???}`>
        results
       </Link>
      </div>

      <div className="schools-nav">
       <Link href=`/${???}/school-a`>
        school-a
       </Link>
       <Link href=`/${???}/school-b`>
        school-b
       </Link>
       <Link href=`/${???}/school-c`>
        school-c
       </Link>
      </div>
     </nav>

    )

Now my guess is do something with useRouter but I'm not sure what to do 🤔🤔. Can someone point me in the right direction?



Solution 1:[1]

This should work for you.

./Navbar.jsx

import { useRouter } from "next/router";

const Navbar = () => {

const router = useRouter();

return (

 <nav>
  <div className="views-nav">
   <Link href=`/results/${router.query.schools}`>
    results
   </Link>
   <Link href=`/statistics/${router.query.schools}`>
    results
   </Link>
  </div>

  <div className="schools-nav">
   <Link href=`/${router.query.views}/school-a`>
    school-a
   </Link>
   <Link href=`/${router.query.views}/school-b`>
    school-b
   </Link>
   <Link href=`/${router.query.views}/school-c`>
    school-c
   </Link>
  </div>
 </nav>

)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ankit Gupta