Linking and Navigating
Next.js provides a built-in routing system that allows you to easily create dynamic client-side routes for your application. Here's a brief overview of how the routing system works in Next.js:
import Link from 'next/link';
function Home() { return (
Home
About Us
Blog Post
export default Home;
Linking to dynamic paths
import Link from 'next/link';
function Posts({ posts }) { return (
{posts.map((post) => (
<Link href={/blog/${encodeURIComponent(post.slug)}}> {post.title}
))}
export default Posts;
Injecting the router
import { useRouter } from 'next/router';
export default function ReadMore() { const router = useRouter();
return ( <button onClick={() => router.push('/about')}> Click here to read more ); }
In this example, we're using the push
method on the router object to navigate to the /about
page when the user clicks a button.
You can also use the replace
method to replace the current URL with a new URL, or the back
method to go back to the previous page in the user's history.