Routing
Linking and Navigation
There are two types to navigate through routes in Next JS
- -Using theLinkComponent
- -Using
useRouter
Hook
<Link> component
<Link>
is the extended version of HTML <a> tag that provides client side navigations between routes. It's primary way to navigate between routes in Next JS.
You can use it by importing it from next/link
, and passing a href
prop to the component.
app/page.tsx
1import Link from 'next/link'
2
3export default function Page() {
4 return <Link href="/dashboard">Dashboard</Link>
5}
Examples
When linking to dynamic segments, you can use template literals and interpolation to generate a list of links. For example, to generate a list of blog posts:
app/page.tsx
1import Link from 'next/link'
2
3export default function PostList({ posts }) {
4 return (
5 <ul>
6 {posts.map((post) => (
7 <li key={post.id}>
8 <Link href={`/blog/${post.slug}`}>{post.title}</Link>
9 </li>
10 ))}
11 </ul>
12 )
13}
Checking Active Links
You can use usePathname()
to determine if a link is active. For example, to add a class to the active link, you can check if the current pathname matches the href of the link:
app/page.tsx
1'use client'
2
3import { usePathname } from 'next/navigation'
4import Link from 'next/link'
5
6export function Links() {
7 const pathname = usePathname()
8
9 return (
10 <nav>
11 <ul>
12 <li>
13 <Link className={`link ${pathname === '/about' ? 'active' : ''}`} href="/">
14 Home
15 </Link>
16 </li>
17 <li>
18 <Link
19 className={`link ${pathname === '/about' ? 'active' : ''}`}
20 href="/about"
21 >
22 About
23 </Link>
24 </li>
25 </ul>
26 </nav>
27 )
28}