Using the Gatsby Link Component to Navigate Between Pages

Now that we’ve been over the basics of working with Gatsby to build a static website, let’s start exploring some of its internals. For this post, I’ll cover the Gatsby Link component, which wraps the underlining Link component of Reach Router, which Gatsby uses internally for routing.

The Link component is used to navigate between internal pages of a Gatsby site instead of using regular anchor (a) tags. The benefits of using Link instead of a regular anchor are the following:

  • Gatsby will intelligently prerender the linked-to content
  • State can be passed to the linked-to page
  • Custom styling or a custom class can be added to links when the active page corresponds with the link.
  • This is a bit more of an advanced use case, but the browser’s history object can be controlled when using the Link component.
Recommended React and GraphQL course

Using the link component is simple, just import it and use it with at least the to prop, which should point to a relative path on the site:

import React from 'react';
import { Link } from 'gatsby';

const AuthorCard = ({ author }) => {
  return (
    <div>
      <img src={author.avatar.children[0].fixed.src} alt={author.name} />
      <p>
        <Link to={`/author/${author.id}/`}>More posts</Link>
      </p>
    </div>
  );
};

export default AuthorCard;

You can also pass in any prop that you’d normally use on an anchor tag. For example, let’s add a title to our link:

<Link
  to={`/author/${author.id}/`}
  title={`View all posts by ${author.name}`}
>
  More posts
</Link>

When linking to an external domain or to a different non-Gatsby site on the same domain, use regular anchor tags.

Active Page

You can style links on the active page differently using either a style object or a class name. For a style object, use the activeStyle prop:

<Link
  to={`/about/`}
  activeStyle={{ textDecoration: "salmon double underline" }}
>
  About Us
</Link>

And to use a class name instead, specify an activeClassName prop:

<Link to={`/about/`} activeClassName="active">
  About Us
</Link>

Linking to the Homepage

To point to the homepage, just use / as the value for the to prop:

<Link to="/">Go home</Link>

Passing-in State

The Link component also accepts a state prop, and the receiving page will have access to what’s passed into that prop via the location prop, at location.state:

<Link to="/" state={{returningVisitor: true}}>
  Go home
</Link>

Linking Programmatically with   navigate

When you need to use the functionality of the Link component, but have to do so programmatically outside of JSX markup, you can use the navigate helper function:

import React from 'react';
import { navigate } from 'gatsby';

handleSubmit = e => {
  e.preventDefault();
  const form = e.target;
  
  // ...do stuff here to submit the form data
  // (e.g.: using the fetch API)

  // Then navigate to the path that corresponds to the form's
  // action attribute 
  navigate(form.getAttribute('action');
};

navigate takes an optional 2nd argument, which should be an object where you can specify state to pass-in and/or if the browser history should be replaced:

navigate(form.getAttribute('action', {
  state: { message: 'Thanks a bunch!' },
  replace: true
});

withPrefix   &   pathPrefix

If your production site is hosted in a sub-directory, you’ll want to set a value for pathPrefix inside the site’s gatsby-config.js file. This way, Gatsby will correctly construct the URLs to link to behind the scenes and things will just work both locally when developing and in production.

You can also make use of the withPrefix helper method to add the site’s prefix manually. This can be helpful where absolute paths are needed:

import React from 'react';
import Helmet from 'react-helmet';
import { withPrefix } from 'gatsby';

const Index = props => {
  return (
    <>
      <Helmet>
        <link rel="icon" sizes="32x32" href={withPrefix('favicon-32x32.png')} />
        <link rel="icon" sizes="192x192" href={withPrefix('favicon-192x192.png')} />
        {/* More stuff here... */}
      </Helmet>

      <div className={props.className}>
        {props.children}
      </div>
    </>
  );
};

export default Index;

🔗 Now you can go ahead and start linking to all the things! For a more in-depth look at Gatsby's Link component, head over to the official documentation.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#