What is Dynamic Routes Next.js?

Dynamic routes in Next.js allow you to create dynamic pages with URLs that depend on specific data or parameters. With dynamic routes, you can handle dynamic content and generate pages based on the provided parameters. Here’s an example of dynamic routes in Next.js:

  1. Create a dynamic page component:
// pages/posts/[postId].js
import React from 'react';
import { useRouter } from 'next/router';

const Post = () => {
  const router = useRouter();
  const { postId } = router.query;

  return (
    <div>
      <h1>Post ID: {postId}</h1>
      {/* Render post content based on postId */}
    </div>
  );
};

export default Post;

In this example, we create a dynamic page component called Post inside the pages/posts directory. The square brackets [] in the file name indicate that it is a dynamic route. The postId is the parameter that will be passed in the URL.

  1. Link to the dynamic page:
// pages/index.js
import React from 'react';
import Link from 'next/link';

const HomePage = () => (
  <div>
    <h1>Home Page</h1>
    <Link href="/posts/1">
      <a>Go to Post 1</a>
    </Link>
    <Link href="/posts/2">
      <a>Go to Post 2</a>
    </Link>
    {/* Add more links with different post IDs */}
  </div>
);

export default HomePage;

In the HomePage component, we create links to the dynamic Post page using the Link component from Next.js. Each link specifies a different postId parameter in the URL.

  1. Access dynamic route parameters:
    If you navigate to /posts/1 or /posts/2, the Post component will be rendered with the corresponding postId parameter. The useRouter hook from Next.js is used to retrieve the dynamic route parameters.

Dynamic routes in Next.js allow you to handle various scenarios, such as fetching data based on the dynamic parameter, generating pages dynamically, and creating SEO-friendly URLs. You can extend this example by fetching and rendering post content based on the postId parameter, implementing pagination, or adding more dynamic routes as per your application’s requirements.

SHARE
By We say

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.