Creating Dynamic Routes in Next.js

Posted by

Next.js is a popular open-source framework for building server-side-rendered (SSR) React applications. It provides a powerful tool for handling dynamic routing, allowing you to create dynamic pages without the need for a heavyweight server or complex setup.

In this article, we will explore the basics of dynamic routing in Next.js and how to get started with creating dynamic pages.

First, let’s create a new Next.js project using the following command:

“`html

Create a new Next.js project

Open your terminal and run the following command:


npx create-next-app my-next-app

“`

After creating the project, you can navigate to the “pages” directory within your project. This is where you will define your dynamic routes.

Let’s create a dynamic page that takes a dynamic parameter, such as a user ID, and displays the user’s details.

“`html

Dynamic routing in Next.js

Create a new file within the “pages” directory called [id].js:


pages/
├── [id].js

In the [id].js file, you can use the following code to define the dynamic page:


import { useRouter } from 'next/router';

function UserPage() {
const router = useRouter();
const { id } = router.query;

return (

User Details

User ID: {id}

);
}

export default UserPage;

Now, when you navigate to /user/123, the page will display the user details for the user with the ID 123.

“`

In the code above, we use the useRouter hook from Next.js to access the dynamic parameter from the URL. Next.js automatically parses the dynamic route and provides it to us through the router.query object.

You can also create nested dynamic routes by creating nested directories within the “pages” directory. For example, if you create a directory called “users” within the “pages” directory and then create a file called [id].js within the “users” directory, you can access dynamic routes such as /users/123.

Dynamic routing in Next.js provides a flexible and simple way to handle dynamic content in your applications. Whether you need to display user details, product information, or any other dynamic content, you can leverage Next.js’s dynamic routing to create dynamic pages with ease.

In conclusion, Next.js makes it easy to handle dynamic routing in your React applications. By following the steps outlined in this article, you can create dynamic pages that take dynamic parameters and display dynamic content based on those parameters. With Next.js, you can build powerful and flexible applications with minimal effort.