Next.js Dynamic Routes

Sonay Kara - Oct 18 - - Dev Community

Buy me coffee

Dynamic routing in Next.js allows developers to build web applications by providing navigation and data fetching based on URL parameters.

Dynamic Routes

In case you don't know the exact segment names in advance and want to create routes from dynamic data, you can use Dynamic Segments that are populated at request time or pre-generated at compile time.

So how to create a dynamic segment?

When you want to create a Dynamic segment in Next.js, you can create a Dynamic Segment by enclosing the name of a folder in square brackets: [folderName].

Now based on this information, let's now create a example folder structure and component

  • Folder structure : app/products/[productId]/page.jsx

Let's code a component that will direct you to the product's detail page when you click on one of the products listed on a shopping site.

Product list component :

export default async function ProductsPage() {

  const res = await fetch('https://api.example.com/products');


  const products = await res.json();

  return (
    <div>
      <h1>Products</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            <a href={`/products/${product.id}`}>
              {product.name}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Product Detail Component :

export default async function ProductDetailsPage({ params }) {
  const { productId } = params;

const res = await fetch(`https://api.example.com/products/${productId}`);

  const product = await res.json();

  return (
    <div>
      <p>{product.title}</p>
      <p>Description: {product.description}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Url : app.com/products/1

Catch-All Segments

Dynamic Segments can be expanded to capture all subsequent segments by adding an ellipsis inside the [...folderName] brackets. And all segments match the component under [...slug] folder

For example, app/products/[...slug]/page.js will match /products/clothes, but also /products/clothes/tops, /products/clothes/tops/t-shirts, and so on.

Optional Catch-all Segments

Catch-all Segments can be made optional by including the parameter in double square brackets: [[...folderName]].

For example, app/products/[[...slug]]/page.js will also match /products, in addition to /products/clothes, /products/clothes/tops, /products/clothes/tops/t-shirts.

The difference between catch-all and optional catch-all segments is that with optional, the route without the parameter is also matched (/shop in the example above).

Conclusion

In conclusion, Next.js dynamic routing offers a powerful and flexible way to handle URL structures in modern web applications. By leveraging file-based routing and dynamic segments, developers can easily create intuitive and scalable navigation for their apps. The ability to fetch data dynamically based on URL parameters further enhances the user experience by delivering relevant content efficiently.

. . . . . . . . . . . . . . . . . . . .
Terabox Video Player