0
0
NextjsHow-ToBeginner · 3 min read

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 Link properly, which breaks navigation.
  • Using href on the inner <a> tag instead of on Link.
  • Forgetting to use an <a> tag inside Link (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 inside Link