Dynamic routes in Nextjs

Dynamic routes in Nextjs


Routes in a Reactjs application is refer to t he URLS which point to different pages in regular web application and page component / component in a Reactjs , Single page application.

Dynamic routes

Regular route ends with http://localhost:3000/about which is static, where the dynamic route have slug or id.

For example a dynamic route show posts can be formed using http://localhost:30/post/:slug. In this context the slug is a variable which can be the one of the post’s slug in a blog. Got it ?

How to create dynamic route in Nextjs ?

Nextjs made the process of creating route easier, create a sub folder inside pages directory and it will treated as a new route, inside that can place index.js which can be the home page for our route.

Dynamic route file name composed of the slug/id/, like [slug].js. The bracket make the filename special and can be access the name through router object.

import React from 'react'
import { useRouter } from 'next/router'
 
const Post = () => {
  const router = useRouter()
  const   {slug}   = router.query 

  return <p>Post: {slug}</p>
}

export default Post

First we created a next-router constant and access the slug through the query object.

The route http://localhost:3000/blog/my-post will print the post slug in this example.

Following Nextjs posts may help you

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

One thought on “Dynamic routes in Nextjs”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.