Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 50 ยท Declarative Routing Basics

Link and NavLink

Learn how React Router's Link differs from a plain anchor, how the to prop works, and how NavLink styles active links with className, style, end and aria-current.

A router is only useful if users can move around, and moving around starts with links. React Router gives you two link components. Link is the everyday one: it looks like an anchor, it is an anchor, but a normal click changes the URL without loading a new page. NavLink is a Link that also knows whether it points at the page you are on, which is what you need for navigation bars, sidebars and tabs.

This lesson explains why Link exists, what its to prop accepts, how NavLink decides it is active, and how to style and describe active links in a way that works for everyone, including screen reader users. The real API is shown read-only, and runnable stand-ins reproduce the click handling and the active-state rules.

Why not just use an anchor?

A plain <a href="/about"> works, but it tells the browser to load a brand new document from the server. Your running React app is thrown away: component state, scroll positions in your own containers, open dialogs and the data you fetched are all gone, and the whole bundle starts again. That is slow and defeats the point of a single-page app.

Link renders the same <a href>, so you keep everything an anchor gives you (middle click, "open in new tab", copy link address, keyboard focus, search engines following it), but on an ordinary click it stops the browser from navigating and asks the router to change the location instead.

JSX
// Real React Router (read-only)
import { Link } from 'react-router';

function Menu() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/products?sort=price">Products by price</Link>
      <Link to="/products/7#reviews">Reviews of product 7</Link>
      <Link to={{ pathname: '/search', search: '?q=router', hash: '#results' }}>Search</Link>
      <a href="https://example.com">An external site: use a normal anchor</a>
    </nav>
  );
}

Use Link for every navigation inside your app and a plain <a> for other sites and for things like mailto: links. (A Link that is given a full URL on another origin behaves like an anchor, but writing <a> states your intent better.)

What the to prop accepts

to is a string or an object:

  • A string can hold a path, a query string and a hash: "/products?sort=price#top".
  • An object has the same parts as the location object from How Routing Works Under the Hood: pathname, search and hash.
  • A relative path such as "edit" or ".." is resolved against the route that renders the link, not against the URL. Relative links get their own lesson, Relative Links and Relative Routing.

Besides to, Link accepts a few props you will meet later:

Prop Effect
replace Replace the current history entry instead of adding one.
state Attach data to the new location, read with useLocation(). See useLocation and Navigation State.
reloadDocument Skip client-side routing and do a normal page load.
preventScrollReset Keep the scroll position instead of resetting it (relevant when scroll restoration is on).
viewTransition Wrap the navigation in a browser view transition.
prefetch Framework mode only: load the next page's code and data early ("intent", "render" or "viewport").

What happens on a click

Not every click should be handled by the router. When someone holds Ctrl or Cmd, they want a new tab; when they press the middle button, they also want a new tab; when the link has target="_blank", the browser must handle it. Link handles a click only when it is a plain primary-button click on a link meant for the same tab, and nobody called preventDefault() in your own onClick first.

flowchart TD
  C["Click on a Link"] --> O{"Your onClick called<br/>preventDefault?"}
  O -->|"yes"| STOP["Router does nothing"]
  O -->|"no"| B{"Primary button, no Ctrl, Cmd,<br/>Shift or Alt, and target is empty or _self?"}
  B -->|"no"| BR["Browser handles it<br/>(new tab, download, etc.)"]
  B -->|"yes"| NAV["preventDefault and navigate<br/>(no page load)"]

Anything that is not a plain click is left to the browser, so links keep behaving like links.

The stand-in below implements exactly this decision. The table is computed with the same function that the live link uses, so you can see why each kind of click is or is not intercepted. Click the live link at the bottom and watch the counter.

Which clicks does Link intercept?

Now try Ctrl+click on the live link in a normal browser tab: the router would step aside. In the real library Link also supports your own onClick: it runs first, and calling event.preventDefault() there cancels the navigation, which the last table row shows.

In a menu, the item for the current page is usually highlighted. NavLink does that bookkeeping. It takes the same props as Link and also tells you three things about the link, which you can use in className, style or children by passing a function:

  • isActive is true when the current URL is the link's target or inside it. A link to /products is active on /products and on /products/7, because /products/7 is a descendant.
  • isPending is true while a navigation to this link is loading (only meaningful with loaders in data mode, see Pending and Optimistic UI).
  • isTransitioning is true during a view transition, if you enabled viewTransition.
JSX
// Real React Router (read-only)
import { NavLink } from 'react-router';

function Sidebar() {
  return (
    <nav>
      <NavLink to="/" end>Home</NavLink>

      <NavLink
        to="/products"
        className={({ isActive, isPending }) =>
          isPending ? 'text-gray-400' : isActive ? 'font-bold text-blue-600' : 'text-gray-700'
        }
      >
        Products
      </NavLink>

      <NavLink to="/orders" style={({ isActive }) => ({ textDecoration: isActive ? 'underline' : 'none' })}>
        {({ isActive }) => (isActive ? 'Orders (you are here)' : 'Orders')}
      </NavLink>
    </nav>
  );
}

Without any configuration, NavLink already helps in two ways. It adds the CSS classes active, pending and transitioning to the anchor when they apply, so you can write plain CSS (nav a.active { font-weight: bold; }), and it sets aria-current="page" on the active link. That attribute tells assistive technology which link represents the current page, so a screen reader says "current page" for it. Relying on color alone would leave those users out, so keep the attribute and add a non-color cue (bold, underline, an icon) as well.

The end prop

"Inside" matching causes a surprise for the top-level item. If every URL started with /, a link to / would be active everywhere. React Router special-cases to="/" so it only matches the root. For other links, end makes the match exact: <NavLink to="/products" end> is active on /products but not on /products/7.

flowchart LR
  P["Link to /products"] -->|"URL /products"| A1["active"]
  P -->|"URL /products/7"| A2["active (descendant)"]
  P -->|"URL /products/7 with end"| A3["not active"]
  P -->|"URL /productsale"| A4["not active (needs a / boundary)"]

Matching works on whole segments: /productsale is not inside /products, and end turns descendants off.

The stand-in below reproduces those rules. Its link component takes className as a function and sets aria-current, just like the real one, apart from isPending, which needs a data router. Tick "end" for Products and open "Product 7".

A NavLink stand-in with end and aria-current

On /products/7 the Products pill stays highlighted until you tick end; on /productsale it never is, because matching respects segment boundaries. The Orders link replaces its label while it is active, which is the children function form.

Putting it together

  • Use Link for ordinary links inside content and NavLink for menus, tabs and sidebars where the current item should look different.
  • Style the active item with the active class or a className function, but also keep a non-color cue, and keep the automatic aria-current="page".
  • Use end on a NavLink that has child routes when only the exact page should be highlighted.
  • Do not call navigate() from a click handler when a link would do: links give users new-tab behavior, a visible URL, and work without JavaScript running yet. Imperative navigation has its own lesson, useNavigate and Imperative Navigation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Link do differently from a plain anchor for an ordinary left click?

    Link renders a real anchor but intercepts a plain click, calls preventDefault and asks the router to navigate, so the running app and its state survive.
  2. 2. A user Ctrl+clicks a Link. What happens?

    Links only intercept plain primary-button clicks. With a modifier key held, the browser's normal behavior (a new tab) is left alone.
  3. 3. On the URL /products/7, is <NavLink to="/products"> active, and what changes with the end prop?

    NavLink counts descendants as active, so /products/7 is inside /products. The end prop requires an exact match, which turns the descendants off.
  4. 4. Which attribute does NavLink set automatically on the active link for assistive technology?

    aria-current="page" marks the link that represents the current page, so screen readers can announce it. It also gives you a hook for CSS.
  5. 5. How do you give a NavLink a different class when it is active?

    className, style and children can all be functions of { isActive, isPending, isTransitioning }. NavLink also adds an automatic active class you can style from plain CSS.

Summary

  • Link renders a real anchor but handles plain clicks in the router, so internal navigation never reloads the app; use a normal <a> for other sites.
  • to can be a string or a { pathname, search, hash } object, and relative values resolve against the route hierarchy.
  • Modified clicks (Ctrl, Cmd, Shift, Alt, middle button) and target="_blank" links are left to the browser, and preventDefault() in your own onClick cancels the navigation.
  • NavLink adds active and pending classes and aria-current="page", and accepts functions for className, style and children that receive isActive, isPending and isTransitioning.
  • A NavLink is active for its target and everything inside it; end limits it to the exact URL, and to="/" only matches the root.
  • Combine color with another visual cue and keep aria-current so the current page is clear to everyone.

Next: 404 Pages and Catch-All Routes