Understanding Dynamic Routes:
Dynamic routes in Next.js allow for the creation of pages with URLs that depend on external data. Unlike traditional static routes, dynamic routes enable the rendering of pages based on dynamic parameters, enhancing flexibility and scalability.Creating Dynamic Routes:
Let's dive into creating dynamic routes in Next.js using the `getStaticPaths` and `getStaticProps` functions. Define a Dynamic Route:- Begin by defining a dynamic route in the pages directory. For instance, create a file named `[slug].js` to handle dynamic URLs.
Implement `getStaticPaths`:
- Inside the dynamic route file, implement the `getStaticPaths` function. This function defines the possible paths for the dynamic route.
- Return an array of objects with `params` containing the dynamic parameters.
Implement `getStaticProps`:
- Next, implement the `getStaticProps` function to fetch data for the dynamic route.
- Utilize the dynamic parameter from `context.params` to fetch the relevant data. Return the fetched data as props.
Render Dynamic Content:
- With `getStaticPaths` and `getStaticProps` configured, you can now render dynamic content on the page using the fetched data.
Example Code:
// pages/[slug].js export async function getStaticPaths() { // Fetch dynamic data to determine paths const paths = [ { params: { slug: 'post-1' } }, { params: { slug: 'post-2' } }, // Add more dynamic paths as needed ]; return { paths, fallback: false // Set to true for incremental static regeneration }; } export async function getStaticProps({ params }) { // Fetch data based on dynamic parameter const postData = await fetch(`https://api.example.com/posts/${params.slug}`); const post = await postData.json(); return { props: { post } }; } export default function Post({ post }) { // Render dynamic content using fetched data return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); }