Next.js File Based Routing (Complex Dynamic Routes) (Part-4)

Posted by Ashutosh on April 06, 2021



If you are new to this page, please follow the previous tutorials before proceeding further.


There is an administrator whose job is to maintain the web application. He can create, edit, delete application users. He does this regularly. He also wants to know how many users are added to the application every month or year. It means we need to update the same component but for different parameters. Here dynamic routing comes into the picture. 


  • Under pages, create a new folder admin. 
  • Create a new folder "users" under admin.
  • create a file [...users].js.

Your directory structure should look like the below illustration.




[...users].js file in Next.js represents the complex Dynamic path. And it will catch all the routes like /admin/users/2021/ or /admin/users/2021/03/.


Update the contents of the file with the following:


import { useRouter } from 'next/router';


function UsersListPage() {
  const router = useRouter();
  const params = router.query.users || [];
  
  return (
    <div>List all the users for { params.join('/') }</div>
  )
}


export default UsersListPage;


Now visit http://localhost:3000/admin/users/2021, you will see "List all the users for 2021".


Visit http://localhost:3000/admin/users/2021/03/, you will see "List all the users for 2021/03".