How to create dynamic routes in Next.js



Image not found!!

In Next.js, dynamic routes allow you to create pages with URLs that have dynamic parameters. These parameters can be used to fetch data and render pages based on the specific value of the parameter. Here's a step-by-step guide on how to create dynamic routes in Next.js:

  1. Create a new Next.js project: If you haven't already, you can create a new Next.js project using the following commands:

    bash
    npx create-next-app my-next-app
    cd my-next-app
  2. Create a pages directory: Inside your Next.js project, create a pages directory if it doesn't already exist. This is where you'll put your page components.

  3. Create a dynamic route page: To create a dynamic route, you can use square brackets [] to indicate a dynamic parameter in the page filename. For example, create a file named [id].js inside the pages directory:

    jsx
    // pages/[id].js import { useRouter } from 'next/router'; const DynamicPage = () => { const router = useRouter(); const { id } = router.query; return ( <div> <h1>Dynamic Page</h1> <p>ID: {id}</p> </div> ); }; export default DynamicPage;

    In this example, the page will receive the id as a query parameter.

  4. Link to the dynamic page: Now, you can create a link to the dynamic page from another page or component. For example, create a file named index.js inside the pages directory:

    jsx
    // pages/index.js import Link from 'next/link'; const HomePage = () => { return ( <div> <h1>Home Page</h1> <Link href="/[id]" as="/123"> <a>Go to Dynamic Page with ID 123</a> </Link> </div> ); }; export default HomePage;

    In this example, clicking the link will take you to the dynamic page with the ID parameter set to "123."

  5. Run your Next.js app: Start your Next.js app using the following command:

    bash
    npm run dev

    Visit http://localhost:3000 in your browser and navigate to the dynamic page using the link you created.

That's it! You've created a dynamic route in Next.js. You can customize the dynamic route parameters based on your application's needs.