As developers, we often encounter the need to build web applications that adapt to changing data and user interactions. Nextjs, a powerful React framework has introduced exciting upadates in its latest release, version 13, that further enhances our ability to create dynamic and flexible web experiences.
One of the things I constantly find myself doing as a frontend developer is displaying content based on a user interaction.
In this article, we will delve into the concept of dynamic routing and how it empowers us to create customizable web pages.
Let's get started.
We are going to have a simple profiles data. This is an array, which contains two objects.
Next, we will create a straightforward interface that displays the two profile names obtained from the data array. Alongside each name, we will provide a clickable link that allows the user to access more information about the selected profile.
Lastly, we will generate a dynamic segment by enclosing the folder's name in square brackets, such as [folderName]. This technique allows us to create flexible routes based on dynamic parameters like [id] or [slug]. In our case, we will create a folder named [slug] within the app directory. Within this folder, we will create a file called page.tsx and insert the provided code snippet.
Here, we applied the filter method to the data by comparing the profile names to the value of params.slug. If there is a match, the corresponding array is returned. Subsequently, we use destructuring to extract the necessary data from the array and update our user interface accordingly.
We will now notice that once the link is clicked, the UI changes to display the description of the corresponding profile being clicked.
Note: This assumes you want to route to localhost:3000/jeff and localhost:3000/peter
To route to http://localhost:3000/profile/john, you've to create the [slug] folder inside a profile a directory. I recommend taking a look at the official doc here
I hope this helps!



Latest comments (0)