#Same url different item
1 messages · Page 1 of 1 (latest)
In Next.js, you can use Dynamic Segments to create routes from dynamic data. A Dynamic Segment can be created by wrapping a file or folder name in square brackets: [segmentName]. For example, [id] or [slug]. Dynamic Segments can be accessed from useRouter.
Here's an example of how you can use a dynamic segment to fetch a specific post:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return <p>Post: {router.query.slug}</p>
}
In this example, the route pages/blog/[slug].js where [slug] is the Dynamic Segment for blog posts. The slug can be 'a', 'b', or 'c' and the corresponding URL will be /blog/a, /blog/b, or /blog/c.
However, if you want to fetch different items (like a post or a category) at the same URL level, you might run into issues because the URL path /slug can only map to one page at a time.
One possible workaround could be to use a query parameter to differentiate between posts and categories. For example, you could use /slug?type=post for posts and /slug?type=category for categories. Then in your page component, you can check the type query parameter to determine whether to fetch a post or a category.
Please note that this is just a workaround and might not be the best solution depending on your specific use case. It's generally recommended to use different URL paths for different types of resources.
For more information, you can refer to the Next.js documentation on Dynamic Routes (https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes).
Please note that the code and information provided are based on the knowledge sources provided and may not cover all possible scenarios or use cases. Always test your code thoroughly to ensure it works as expected.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@buoyant marlin kapa.ai is still learning and improving, please let us know how it did by reacting below