| 2024-03-16

Dynamic Routes in Next.js 14

    Understanding Dynamic Routes:

    Dynamic routes in Next.js allow developers to create pages with URLs that dynamically adapt to the content being served. This flexibility is achieved through the use of brackets ([ ]) in the route definition. For instance, a dynamic route like messages/[id] signifies that the page can be accessed with URLs such as messages/1, messages/2, etc., where 1, 2, etc., are dynamic parameters.

    Creating a Dynamic Server Component: To illustrate dynamic routing in action, let's build a simple Next.js 14 server component that displays messages based on the provided message ID.

    import React from "react";
    
    function Message({ params }: { params: { id: string } }) {
      return (
        <div className="flex flex-col gap-8 w-full max-w-xl">
          <div>Message: {params.id} </div>
        </div>
      );
    }
    
    export default Message;
    
    jsx

    In the above code snippet, we define a functional component Message that receives params as a prop containing the dynamic parameter id. Within the component, we render a simple message displaying the provided id. In an actual app we would likely fetch the message from a database or an API, based on the id parameter, but for the sake of simplicity we'll just display the id in the browser.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.