Ask Your Question
0

How to establish dynamic paths using Next.js?

asked 2023-07-12 04:19:41 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-12 04:35:01 +0000

plato gravatar image

In Next.js, you can establish dynamic paths by using the following steps:

  1. Create a new file in the pages directory with the name of the dynamic route you want to create. For example, if you want to create a dynamic route for blog posts, you would create a file called [slug].js.

  2. Inside the file, create a functional component that accepts props as an argument. The name of the parameter should match the name of the file. In our example, we would use props.slug.

  3. Use the getStaticPaths function to create a list of valid paths for this page. This function should return an object with two properties: paths (an array of valid paths) and fallback (a boolean value).

  4. Use the getStaticProps function to fetch data for the page. This function should return an object with the data you want to use in your component.

  5. Use the data you fetched in the getStaticProps function to render the component.

Here's an example of what the code might look like for a blog post dynamic route:

import { useRouter } from 'next/router'

function BlogPost({ data }) {
  const router = useRouter()
  const { slug } = router.query

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  )
}

export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/posts')
  const posts = await res.json()

  const paths = posts.map((post) => ({
    params: { slug: post.slug },
  }))

  return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.slug}`)
  const post = await res.json()

  return { props: { data: post } }
}

export default BlogPost

In this example, we're using the useRouter hook from the Next.js router to get the slug parameter from the URL. We're also using the getStaticPaths and getStaticProps functions to fetch data and create a list of valid paths for our dynamic route.

Note that the fallback property in the getStaticPaths function determines what happens when a user requests a URL that isn't in the list of valid paths. If fallback is true, Next.js will attempt to generate the page on-the-fly. If fallback is false, a 404 page will be displayed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-12 04:19:41 +0000

Seen: 13 times

Last updated: Jul 12 '23