Using dynamic routes in Next.js lets you make pages that change their content based on the URL parameters. Here's how to do it:
Define a Dynamic Route:
Create a file in the
pages
directory with square brackets[]
to indicate that it's a dynamic route. For example, if you want to create a dynamic route for individual blog posts, you might create a file named[slug].js
in thepages/posts
directory.// pages/posts/[slug].js import { useRouter } from 'next/router'; const Post = () => { const router = useRouter(); const { slug } = router.query; return <h1>Post: {slug}</h1>; }; export default Post;
Access URL Parameters:
Inside the page component, you can access the dynamic parameter (in this case,
slug
) using theuseRouter
hook from Next.js. Therouter.query
object will contain the dynamic parameter.Create Dynamic Content:
Once you have access to the dynamic parameter, you can use it to fetch data or generate dynamic content for the page. For example, you might fetch the specific blog post corresponding to the slug from a data source (such as a CMS or database) and render it on the page.
// Fetching data for dynamic content import { useRouter } from 'next/router'; import { getPostBySlug } from '../../lib/posts'; const Post = ({ post }) => { return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); }; export async function getServerSideProps({ params }) { const { slug } = params; const post = await getPostBySlug(slug); return { props: { post, }, }; } export default Post;
In this example, the
getServerSideProps
function is used to fetch the data for the specific post based on the slug parameter. This data is then passed as props to the page component.Navigate to Dynamic Routes:
You can navigate to dynamic routes using Next.js's
Link
component or therouter.push
method. For example:import Link from 'next/link'; const PostList = ({ posts }) => { return ( <ul> {posts.map((post) => ( <li key={post.slug}> <Link href={`/posts/${post.slug}`}> <a>{post.title}</a> </Link> </li> ))} </ul> ); };
This code snippet creates a list of posts where each post title is a link to its corresponding dynamic route.
By doing this, you can make Next.js pages that change based on URL parameters. This method lets you have flexible and dynamic routing in your Next.js projects.