Dynamic routing : Omnath Dubey

Dynamic routing is a technique used in web development that involves defining routes with parameters that can change at runtime. This allows web applications to handle dynamic content and provide a more flexible and customizable user experience. In Next.js, dynamic routing is supported out-of-the-box, making it easy to create dynamic pages and content.

In Next.js, dynamic routes are defined using square brackets ("[]") in the page file name or in the route string. For example, a page file named "[id].js" would match any route that contains a single parameter named "id". The value of the "id" parameter can then be accessed using the "useRouter" hook, which is provided by the "next/router" module.

Here's an example of how to define a dynamic route in Next.js:

// pages/posts/[slug].js import { useRouter } from 'next/router' function Post() { const router = useRouter() const { slug } = router.query return ( <div> <h1>{slug}</h1> <p>This is the page for the post with slug {slug}.</p> </div> ) } export default Post


In this example, the "slug" parameter is defined in the page file name using square brackets. The "useRouter" hook is then used to access the value of the "slug" parameter, which is used to display the content for the corresponding post.

Dynamic routing can be used to create a wide variety of dynamic content, such as blog posts, product pages, and user profiles. It provides a powerful way to create custom user experiences and can greatly improve the flexibility and versatility of web applications.