Gatsby Link is an enhanced Link component for Gatsby sites that extends the functionality of Reach Router's Link component with intelligent resource prefetching capabilities. The component automatically prefetches linked pages when they come into the viewport using the Intersection Observer API, significantly improving site navigation performance by preloading resources before users click links.
npm install gatsby-linkNote: This package is now exported from the main gatsby package. You should import from gatsby instead of gatsby-link directly.
import { Link, navigate, withPrefix, parsePath } from "gatsby";For direct import from gatsby-link (legacy):
import { Link, navigate, withPrefix, withAssetPrefix, parsePath } from "gatsby-link";Note: gatsby-link extends functionality from @gatsbyjs/reach-router, which provides the underlying routing capabilities.
CommonJS:
const { Link, navigate, withPrefix } = require("gatsby");import React from "react";
import { Link, navigate } from "gatsby";
function Navigation() {
return (
<nav>
{/* Basic link with prefetching */}
<Link to="/about">About</Link>
{/* Link with active styling */}
<Link
to="/blog"
activeClassName="active"
activeStyle={{ color: "red", fontWeight: "bold" }}
>
Blog
</Link>
{/* Link with state passing */}
<Link
to="/contact"
state={{ fromNavigation: true }}
>
Contact
</Link>
{/* Programmatic navigation */}
<button onClick={() => navigate("/search")}>
Go to Search
</button>
</nav>
);
}Gatsby Link is built around several key components:
The main Link component for creating navigational links in Gatsby applications with automatic prefetching.
/**
* Enhanced Link component for Gatsby sites with prefetching support
* Automatically prefetches linked pages when they enter the viewport
*/
interface GatsbyLinkProps<TState> extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
/** A class to apply when this Link is active */
activeClassName?: string;
/** Inline styles for when this Link is active */
activeStyle?: object;
/** Click event handler */
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
/** Classes the link as highlighted if there is a partial match via the `to` being prefixed to the current url */
partiallyActive?: boolean;
/** Used to declare that this link replaces the current URL in history with the target */
replace?: boolean;
/** Used to pass state data to the linked page */
state?: TState;
/** The URL you want to link to */
to: string;
}
/**
* This component is intended _only_ for links to pages handled by Gatsby.
* For links to pages on other domains or pages on the same domain not handled
* by the current Gatsby site, use the normal `<a>` element.
*/
declare class Link<TState = any> extends React.Component<GatsbyLinkProps<TState>, any> {}Usage Examples:
import { Link } from "gatsby";
// Basic link
<Link to="/about">About Us</Link>
// Link with active styling
<Link
to="/products"
activeClassName="current-page"
activeStyle={{ borderBottom: "2px solid blue" }}
>
Products
</Link>
// Partially active link (highlights when URL starts with /blog)
<Link to="/blog" partiallyActive={true} activeClassName="active">
Blog
</Link>
// Link with state passing
<Link
to="/product-details"
state={{ productId: 123, fromCategory: "electronics" }}
>
View Product
</Link>
// Link that replaces history entry
<Link to="/login" replace={true}>
Login
</Link>
// Link with click handler
<Link
to="/external-redirect"
onClick={(e) => {
// Track analytics before navigation
analytics.track("link_clicked", { destination: "/external-redirect" });
}}
>
External Redirect
</Link>Function for navigating programmatically, useful for form submissions and other non-link navigation scenarios.
/**
* Navigate programmatically to pages within your Gatsby site
* Sometimes you need to navigate to pages programmatically, such as during form submissions
*/
declare const navigate: {
/** Navigate to a specific path with optional navigation options */
(to: string, options?: NavigateOptions<any>): void;
/** Navigate backward or forward in browser history by number of steps */
(to: number): void;
};
interface NavigateOptions<TState = any> {
/** Replace the current history entry instead of pushing a new one */
replace?: boolean;
/** State data to pass to the target page */
state?: TState;
}Usage Examples:
import { navigate } from "gatsby";
// Basic navigation
navigate("/thank-you");
// Navigation with state
navigate("/results", {
state: { searchQuery: "react", filters: ["tutorial", "beginner"] }
});
// Replace current history entry
navigate("/login", { replace: true });
// Navigate backward/forward in history
navigate(-1); // Go back one page
navigate(2); // Go forward two pages
// Form submission example
function ContactForm() {
const handleSubmit = async (formData) => {
await submitForm(formData);
navigate("/thank-you", {
state: { formSubmitted: true, email: formData.email }
});
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
</form>
);
}Utility functions for handling path prefixes in Gatsby applications.
/**
* Add the site's path prefix to a URL path
* Handles the path prefix configuration set in gatsby-config.js
*/
declare const withPrefix: (path: string) => string;
/**
* Add the site's asset prefix to a path
* Uses the global PATH_PREFIX for assets like images and static files
*/
declare const withAssetPrefix: (path: string) => string;Usage Examples:
import { withPrefix, withAssetPrefix } from "gatsby";
// Add path prefix to internal links
const prefixedPath = withPrefix("/about");
// If pathPrefix is "/my-site", returns "/my-site/about"
// Add asset prefix to static assets
const assetPath = withAssetPrefix("/images/logo.png");
// Returns prefixed path for static assets
// Use in components
function Header() {
return (
<header>
<img src={withAssetPrefix("/images/logo.png")} alt="Logo" />
<Link to={withPrefix("/about")}>About</Link>
</header>
);
}
// Path prefix handling for dynamic paths
function generateSitemapUrls(pages) {
return pages.map(page => ({
url: withPrefix(page.path),
lastmod: page.lastModified
}));
}Utility function for parsing URL paths into components.
/**
* Parse a URL path into its component parts
* Useful for URL manipulation and analysis
*/
declare function parsePath(path: string): {
/** The pathname portion of the URL */
pathname: string;
/** The search/query string portion (including '?') */
search: string;
/** The hash fragment portion (including '#') */
hash: string;
};Usage Examples:
import { parsePath } from "gatsby";
// Parse a complete URL path
const parsed = parsePath("/blog/post-1?tag=react&sort=date#comments");
console.log(parsed);
// {
// pathname: "/blog/post-1",
// search: "?tag=react&sort=date",
// hash: "#comments"
// }
// Handle edge cases
const emptyPath = parsePath("");
// { pathname: "/", search: "", hash: "" }
const pathOnly = parsePath("/about");
// { pathname: "/about", search: "", hash: "" }
// Use in custom link processing
function createCanonicalUrl(path) {
const { pathname, search } = parsePath(path);
return `https://example.com${pathname}${search}`;
}Gatsby Link automatically prefetches linked pages when they come into the viewport using the Intersection Observer API. This happens transparently and requires no additional configuration.
How it works:
Links automatically receive active styling when they match the current page URL.
// Exact match (default behavior)
<Link to="/about" activeClassName="current">About</Link>
// Partial match (useful for navigation sections)
<Link to="/blog" partiallyActive={true} activeClassName="active">
Blog Section
</Link>
// Combined with inline styles
<Link
to="/products"
activeStyle={{
color: "#007acc",
borderBottom: "2px solid #007acc",
fontWeight: "600"
}}
>
Products
</Link>Gatsby Link automatically detects external URLs and renders them as regular anchor tags instead of router links.
// This becomes a regular <a> tag automatically
<Link to="https://external-site.com">External Link</Link>
// Local links use Gatsby's router
<Link to="/internal-page">Internal Link</Link>Pass data between pages using the state prop, accessible via location.state in the target component.
// Source page
<Link
to="/product-details"
state={{
productId: 123,
category: "electronics",
referrer: "homepage"
}}
>
View Product
</Link>
// Target page component
function ProductDetails({ location }) {
const { productId, category, referrer } = location.state || {};
return (
<div>
<h1>Product {productId}</h1>
<p>Category: {category}</p>
<p>Came from: {referrer}</p>
</div>
);
}Gatsby Link includes built-in validation and error handling: