One of the more powerful features of Nextjs
is how it handles regular and dynamic routing. In this video we will go through how to setup a single basic and dynamic route within the pages
directory using Nextjs
's file routing and render some content.
Domitrius Clark: [0:00] In Next.js, routing is determined by the files and folders within its Pages directory.
[0:05] As you can see here, we're exporting a function that returns some JSX. At localhost:3000, that JSX gets returned.
[0:15] Let's create a couple of folders within our Pages directory -- one named User, and another folder named Users. In our Users directory, we'll create a new file of index.js, which will serve as the base users route. We'll export a default function again, which will return some JSX.
[0:40] Creating a folder in the Pages directory and creating an index.js inside that folder -- it serves as the base route. If we visit localhost:3000/users, you'll see we get the Users page. In our User directory, we'll create bracket-id.js, which is how we'll deal with dynamic routing. We'll import useRouter, from next/router, and then we'll export a default function.
[1:11] Then we'll define a const of router and set it to our useRouter declaration. Then we'll destructure id from router.query, which will allow us to pull parameters from our url. Finally, we'll return some JSX that allows us to pull that id down and see it inside of our render.
[1:37] Now we've hooked into the router, grabbed the id off of our query, and are rendering it. If we head over to the url and add user/122, you'll see in our render we get that id.