Next Js dynamic routes πŸ”

Next Js dynamic routes

Defining routes by using predefined paths is not always enough for complex applications. In Next.js you can add brackets to a page ([param]) to create a dynamic route (a.k.a. url slugs, pretty urls, and others).

You should know!

useRouter is a React Hook, meaning it cannot be used with classes. You can either use withRouter or wrap your class in a function component.

useRouter ❀️‍πŸ”₯

next js folder structure looks like

Next Js dynamic routes

Consider the following page πŸ‘‡πŸΌ

pages/_app.js:

import { useRouter } in in _app.js file and console the router and you will see how many features and methods in useRouter.

import '../styles/globals.css' import { useRouter } from 'next/router' function App({ Component, pageProps }) { const router = useRouter() console.log(router, 'router') return <Component {...pageProps} /> } export default App

you will see like this πŸ‘‡πŸΌ

console the useRouter in next js

Tip

Read our docs for Linking between pages to learn more.

Dynamic route 🀸🏽

Create blog Folder in πŸ‘‰ Next Js Pages/ when it's done create index.js page in blog folder and import the data from from data.js file read the below file from more information. πŸ‘‡πŸΌ

index.js

import Link from 'next/link' import { data } from './data.js' function index() { return ( <div> <span>blog Page</span> {data.map((x) => { return ( <div key={x.id}> <h1>{x.title}</h1> <Link href={`/blog/${x.slug}`}>Go to pages/blog/[slug].js</Link> </div> ) })} </div> ) } export default index

create data.js file in blog folder for easy your code and work also easy understand useRouter() in Next Js.

data.js

export const DemoData = [ { id: 1, slug: 'what-is-html', title: 'What is HTML?', }, { id: 2, slug: 'what-is-css', title: 'What is css?', }, ]

when it's done create slug or id dynamic page using [] array brackets. like πŸ‘‡πŸΌ

[slug].js

import React from 'react' import { useRouter } from 'next/router' function blog() { const router = useRouter() const { slug } = router.query let demo = data.find((x) => x.slug === slug) return ( <div> <span>dynamic page</span> <h1>{demo.title}</h1> </div> ) } export default blog

destructure the { slug } from router.query and import Mock data from data.js file and find() the data of slug which is equal the router.query slug.