Next.js - Routing
- Routing in Next.js allows for navigation between different pages or views in a web application.
- Next.js provides client-side navigation using the
Link
component for seamless page transitions. - It also supports dynamic routing for creating dynamic routes based on parameters in the URL.
1. Client-side Navigation
Client-side navigation allows users to navigate between pages without full page reloads, providing a smoother user experience.
<Link href="/about"> <a className="link">About</a> </Link>
2. Dynamic Routing
Dynamic routing enables the creation of routes based on parameters in the URL, allowing for flexible and dynamic page structures.
// pages/post/[id].js import { useRouter } from 'next/router'; export default function Post() { const router = useRouter(); const { id } = router.query; return ( <div> <h1>Post {id}</h1> </div> ); }
3. Example
Here's an example demonstrating client-side navigation and dynamic routing in a Next.js project:
Create two pages: index.js
and post/[id].js
in the pages
directory:
// index.js import Link from 'next/link'; export default function Home() { return ( <div> <h1>Welcome to Next.js!</h1> <Link href="/post/1"><a>Go to Post 1</a></Link> </div> ); } // post/[id].js import { useRouter } from 'next/router'; export default function Post() { const router = useRouter(); const { id } = router.query; return ( <div> <h1>Post {id}</h1> </div> ); }
Conclusion
Routing in Next.js is essential for creating multi-page web applications with seamless navigation. By leveraging client-side navigation and dynamic routing, developers can build interactive and dynamic user interfaces that enhance the user experience.
Comments
Post a Comment