How to Use Link Component in Next.js for Navigation
In Next.js, use the
Link component from next/link to create client-side navigation between pages. Wrap the destination URL in href and place the clickable content inside the Link tags for fast, seamless page transitions.Syntax
The Link component is imported from next/link. You use it by wrapping an <a> tag or any clickable element inside <Link href="/path"></Link>. The href attribute defines the destination URL.
- href: The path or URL to navigate to.
- children: The clickable content, usually an
<a>tag.
jsx
import Link from 'next/link'; function Component() { return ( <Link href="/about"> <a>About Page</a> </Link> ); }
Example
This example shows a simple navigation menu using the Link component to move between Home and About pages without full page reloads.
jsx
import Link from 'next/link'; export default function Nav() { return ( <nav> <ul> <li> <Link href="/"> <a>Home</a> </Link> </li> <li> <Link href="/about"> <a>About</a> </Link> </li> </ul> <style jsx>{` nav ul { display: flex; list-style: none; gap: 1rem; padding: 0; } a { text-decoration: none; color: blue; } a:hover { text-decoration: underline; } `}</style> </nav> ); }
Output
A horizontal navigation bar with two links: 'Home' and 'About'. Clicking them changes the page without full reload.
Common Pitfalls
Common mistakes include:
- Not wrapping the clickable element inside
Linkproperly, which breaks navigation. - Using
hrefon the inner<a>tag instead of onLink. - Forgetting to use an
<a>tag insideLink(required for accessibility and styling).
Always put href on Link and wrap the clickable text inside an <a> tag.
jsx
/* Wrong way: href on <a> instead of Link */ import Link from 'next/link'; function Wrong() { return ( <Link> <a href="/about">About</a> </Link> ); } /* Right way: href on Link, <a> inside */ function Right() { return ( <Link href="/about"> <a>About</a> </Link> ); }
Quick Reference
- Import:
import Link from 'next/link' - Usage:
<Link href="/path"><a>Text</a></Link> - Purpose: Enables client-side navigation without full page reload
- Accessibility: Always use an
<a>tag insideLink
Key Takeaways
Use the Link component from next/link with href to enable client-side navigation.
Always wrap clickable content inside an tag within Link for accessibility and styling.
Do not put href on the tag; it belongs on the Link component.
Link enables fast page transitions without full reloads in Next.js apps.
Check your Link usage to avoid broken navigation or accessibility issues.