Routing and Navigation
Learn how to navigate between pages and internal links in Gatsby.
We'll cover the following
Introduction to routing
What is a website without a means to navigate between the different pages? This question brings us to Gatsby’s Link
component and the navigate
helper function. These make it possible for us to navigate and move between internal pages in Gatsby.
The Link
component
This built-in component provided by Gatsby enables us to navigate between internal pages. We used this component in our PostCard
component. This is why clicking on any of the card items immediately opens to the prefetched page. This is very unlike the behavior of the navigation links in our header component. Clicking on any of these leads to a full page load of the requested page. This is because we still use the traditional anchor (a
) tags for these links.
Why use the Link
component?
The Gatsby Link
component has additional advantages over the anchor tag when used to link between pages.
-
Preloading and pre-fetching
When the
Link
component is used, Gatsby smartly fetches and loads the page’s content and resources as soon as the link gets into the viewport—even more so when the viewer’s mouse hovers over the link. This is why the requested page loads almost immediately after clicking, with very little latency and load time. -
Passing down state
This component also allows us to pass down state and data to the linked-to page. We see this in action soon enough.
-
Custom styling
When we use
a
tags to link to pages, we find it difficult to quickly identify active links, that is, links that match with the active page. TheLink
component accepts anactiveStyle
prop that helps us customize the look of active links. We see this in action, too.
How to use the Link
component
We have to make changes to our header.js
component file to see this component in action. The only major change we make is to replace the a
tags with the Link
component. We also write a custom style rule for our active links.
We need to replace the file content with the code below:
Get hands-on with 1400+ tech skills courses.