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
- Array map to new type in TypeScript
- Create a dark mode theme switch in Nextjs 13
- Zustand, a minimal store for Rreactjs
- How to use styles in Remix
- Not found page UI in Nextjs 13
- Implementing a loading UI in Nextjs 13
- How to fetch data in Nextjs 13 appDir
- How to use Turbopack build tool in Nextjs project
- Try Next 13 experimental App feature
- Integrate Hygraph with Svelte, React, Vue
One thought on “Dynamic routes in Nextjs”