Skip to main content

Archive

Show more

Nextjs Dynamic Routing

Next.js - Dynamic Routing

Dynamic routing in Next.js allows for creating routes based on parameters in the URL, providing flexibility in handling dynamic content.


1. Basic Dynamic Routing

To implement dynamic routing in Next.js, utilize file-based dynamic routing by creating files with square brackets ([ ]) in the pages directory.

<pages>
  <-- pages/[id].js -->
</pages>

In this example, a file named [id].js in the pages directory corresponds to the route /pages/:id, where :id is a dynamic parameter.


2. Accessing Dynamic Parameters

Dynamic parameters can be accessed within Next.js components using the useRouter hook from the next/router module.

import { useRouter } from 'next/router';

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

    return (
        <div>
            <h1>Dynamic Page: {id}</h1>
        </div>
    );
}

export default DynamicPage;

In this example, the router.query object contains the dynamic parameter id, which can be accessed within the component.


3. Nested Dynamic Routing

Next.js supports nested dynamic routing, allowing for complex route structures. Nested folders with dynamic parameter files represent nested routes.

<pages>
  <-- pages/products/[category]/[id].js -->
</pages>

In this example, a file named [id].js within the products/[category] directory corresponds to the route /products/:category/:id.


Conclusion

Dynamic routing in Next.js offers powerful capabilities for handling dynamic content and building complex route structures. By utilizing file-based dynamic routing and accessing dynamic parameters within components, developers can create flexible and dynamic web applications.

Comments