Understanding Dynamic Routing in NextJS

Routing in Next JS is super easy!! It's just creating a based on file structure which uses app and page.js for any page.

All you require to create a route for a new page is to create a new folder in the workspace and bam!! you got the the new ficking route for that page.

Let's take an example, you want to create a page for showing your anime collection in probably your portfolio ( don't do this ). All you have to do is to create a folder names " my-animes " and you will have a different page for that with the link " portfolio.com/my-animes ". Super Easy!!

But ever wondered what will you do when you don't really have any specific name for that page or the name of the page is dynamic which changes based on the data. It's that time when, dynamic routing comes to the play.

See!! routing is a really important aspect for the SEO ( search engine optimization ) for the website. As explained in the below article, SEO mostly comes with the user engagement and URLs can play a vital part in it.

The way you create and manage your URLs can affect the user's engagement with your website and hence the SEO.

So, to create a simple route on NextJs all you have to do is to create a folder with the route name and it will be created.

But now when you want to create any route which will change based on some data that may be from database or from any other page, creation of dynamic routes comes to play.

Create a folder with it's name in [ ] bracket, just like how I did in the above image. This will create the dynamic route after blogs like /blogs/[id] ( for specific blog ).

Just like this here, it can be created.

I recently made a tweet exploring dynamic routes in NextJS. Checkout for more practical explanation.

Now you many wonder how could we can access the elements of that link in the code or what if we want to create more dynamic page inside the same dynamic route ?

You can access the id by passing params. Lemme give you an example below:

import React from 'react'

const page = ({params}) => {
  return (
    <div>{params.id}</div>
  )
}

export default page

Here, params is used to access the elements of the link.

Now, if you want to create some dynamic links inside another link, just create another folder in [id], example - /blogs/[id]/[author]. etc..etc

Routing in nextjs is one of the best feature of it which makes development on it easier and more convenient on nextjs.

What are your thoughts on it and what did you created with the nextjs, comment down below.

Until then Sayonara

Did you find this article valuable?

Support Explore with Ojas by becoming a sponsor. Any amount is appreciated!