Tutorial

Using the Gatsby Link Component to Navigate Between Pages

Published on May 19, 2019
author

Alligator.io

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.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.