Setting Up Dynamic Routes in Next.js
Next.js dynamic routes offer flexibility to create pages based on dynamic parameters, allowing for versatile data handling.
Guide to Setting Up Dynamic Routes
- Create a folder with the desired dynamic parameter enclosed in square brackets, e.g.,
[id]
. - In this folder, create a file named
page.js
to represent the dynamic page content. - Access the dynamic parameter using destructuring in the function parameters, typically
params.id
.
Detailed Breakdown
- Start by defining a list of items, such as drinks.
- Create a wrapper page for each item, utilizing a unique identifier (e.g., ID) to fetch specific data.
- Set up the dynamic route by creating a folder with square brackets containing the parameter name, like
[id]
. - Inside this folder, create the page file, ensuring to access the parameter using the same name (e.g.,
params.id
).
Example Directory Structure
[project_root]
├── pages
│ └── drinks
│ └── [id]
│ └── page.js
By navigating to /drinks/[id]
, where [id]
represents the dynamic parameter, Next.js handles the routing and rendering of the corresponding page.
Accessing the Dynamic Parameter
With this setup, navigating to /drinks/[id]
will log the dynamic parameter value to the console.
Post a Comment
0Comments