Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Pages and Routing

Link and Navigation

Navigate a Gatsby site with the Link component, active styling, partiallyActive, state, navigate() for code-driven redirects, prefetching and external links.

Links connect your pages, and in Gatsby they do more than in plain HTML. The Link component renders a normal anchor tag, but it also prefetches the target page in the background and navigates without a full reload. This is a large part of why Gatsby sites feel instant. This lesson covers Link, active link styling, passing state, navigating from code and when not to use Link.

Gatsby code is read-only here. Stand-ins model the behaviors in plain JavaScript.

JSX
// real Gatsby, read-only
import * as React from "react"
import { Link } from "gatsby"

const Nav = () => (
  <nav>
    <Link to="/">Home</Link>
    <Link to="/about/">About</Link>
    <Link to="/blog/first-post/">First post</Link>
  </nav>
)

Use to, not href. The result in the HTML is an ordinary <a href="/about/">, so it works without JavaScript and search engines can follow it.

Important rules:

  • Use Link only for internal URLs (pages of your own site). For external sites and files use a regular <a href>.
  • Match your trailingSlash policy from gatsby-config so links do not trigger redirects.
  • Links to anchors on the same page work with <Link to="#section">, but plain <a href="#section"> is just as good.

How prefetching works

When a Link becomes visible in the viewport, Gatsby downloads the page's JavaScript chunk and its data (the JSON from the page query) with low priority. On click, everything is already in memory, so rendering is nearly immediate. You get this for free for every Link. On slow connections or with data saving enabled, Gatsby reduces prefetching.

sequenceDiagram
  participant V as Visitor
  participant L as Link
  participant G as Gatsby runtime
  V->>L: link scrolls into view
  L->>G: prefetch page chunk and data
  G-->>L: cached in memory
  V->>L: clicks
  L->>V: renders instantly, URL updated

The click only swaps what is already downloaded.

To style the link of the current page, use activeClassName or activeStyle:

JSX
<Link to="/blog/" activeClassName="active">Blog</Link>
<Link to="/blog/" partiallyActive={true} activeClassName="active">Blog</Link>

Without partiallyActive, the link is "active" only on exactly /blog/. With partiallyActive, it is also active on /blog/first-post/, which is what you want for a section menu. A special case: the home link to="/" with partiallyActive would be active everywhere, so leave partiallyActive off for it.

For more control, getProps receives isCurrent and isPartiallyCurrent and returns props for the anchor:

JSX
<Link
  to="/docs/"
  getProps={({ isPartiallyCurrent }) =>
    isPartiallyCurrent ? { className: "nav-link active" } : { className: "nav-link" }
  }
>
  Docs
</Link>

Passing state and replacing history

Link can send state that does not appear in the URL. The destination reads it from location.state:

JSX
<Link to="/checkout/" state={{ from: "cart", coupon: "SPRING" }}>Checkout</Link>

// on the destination page
const Checkout = ({ location }) => <p>Came from {location.state?.from}</p>

Use replace to replace the current history entry instead of adding one, so the back button skips this step:

JSX
<Link to="/login/" replace>Sign in</Link>

State disappears if the visitor opens the URL directly, so always provide a fallback.

Use navigate after an action, such as submitting a form:

JSX
import { navigate } from "gatsby"

const handleSubmit = async (event) => {
  event.preventDefault()
  await saveForm()
  navigate("/thanks/", { replace: true, state: { name: "Ada" } })
}

navigate also works for external-looking paths, but for real external URLs use window.location.

Linking with a path prefix

When a site is hosted under a sub-path (for example example.com/docs), you set pathPrefix in the config and build with --prefix-paths. Link and navigate add the prefix for you, so never write it by hand. A plain <a href="/about/"> would not get the prefix, another reason to use Link for internal URLs.

This stand-in is not Gatsby. It implements the decision rules of Link: exact and partial active matching, and prefetching on visibility.

JS Stand-in: active matching

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: navigate with history and state

JS Stand-in: navigate, replace and back

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For accessibility, make link text meaningful on its own. "Read the deployment guide" works for screen reader users who list all links; "click here" does not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which prop sets the destination of a Gatsby Link?

    Link uses to. The rendered anchor still has an href.
  2. 2. What does partiallyActive do?

    It makes /blog/ count as active on /blog/first-post/ too.
  3. 3. When should you use a plain <a> instead of Link?

    Link is for internal navigation only. External URLs and files need a normal anchor.
  4. 4. Which function navigates after a form submit?

    navigate is imported from gatsby and accepts options such as replace and state.

Summary

  • Link renders a real anchor, navigates client-side and prefetches visible targets.
  • Use it for internal URLs only; external URLs and files use <a>.
  • Style current links with activeClassName, partiallyActive or getProps.
  • state passes data without changing the URL, and replace avoids a history entry.
  • navigate() handles redirects from code, and both respect pathPrefix.

Next: Layouts and Shared Components