Learn Gatsby · 2/12

Pages and Routing: Building the Site Skeleton

9 min read

Pages and Routing: Building the Site Skeleton 骨

Welcome back! So, you've got the basic building blocks of a Gatsby site. Now, let's give it some shape. A website isn't just one page; it's a collection of pages—a home page, an about page, a contact page, and so on. This guide is all about creating that skeleton, defining the rooms in our digital house, and building the hallways that connect them.

We'll be covering how to create pages, link between them seamlessly, build reusable structures to keep our code clean, and even how to gracefully handle it when a user gets lost.


1. File-based Routing: Creating Static Pages Automagically ✨

The Problem: In many older web frameworks, if you wanted to create a new page at a specific URL (like /about), you'd have to go into a central configuration file and manually map the URL path to the page's code file. For a site with 50 pages, that's 50 manual entries. It's tedious, and it's easy to make a typo and break a link.

The Solution: Gatsby's "Convention over Configuration"

Gatsby takes a beautifully simple approach. It assumes that if you create a file in a special folder, you want a page for it. This is called file-based routing.

Definition: Gatsby automatically creates a page and a URL path for every JavaScript file you place inside the src/pages/ directory. The URL is derived directly from the filename.

Let's imagine the src/pages directory is a magical blueprint machine. Whatever drawing (React component) you put inside, the machine automatically builds a corresponding room (a web page) in your site.

How It Works Under the Hood:
During the build process, Gatsby's internal machinery scans the src/pages/ folder. For each file it finds, it generates a page with a path that mirrors the file's name. The one exception is index.js, which maps to the root / path of your site.

Hands-On Example:

Let's create three basic pages. In your Gatsby project, your src/pages/ directory will look like this:

stylus
/src
└── /pages
    ├── index.js     // This will be our homepage -> yoursite.com/
    ├── about.js     // This will be our about page -> yoursite.com/about
    └── contact.js   // This will be our contact page -> yoursite.com/contact

src/pages/index.js

javascript
import React from 'react';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to the Homepage!</h1>
      <p>This is the main entry point of our site.</p>
    </div>
  );
};

export default HomePage;

src/pages/about.js

javascript
import React from 'react';

const AboutPage = () => {
  return (
    <div>
      <h1>About Us</h1>
      <p>Here is some information about our awesome company.</p>
    </div>
  );
};

export default AboutPage;

src/pages/contact.js

javascript
import React from 'react';

const ContactPage = () => {
  return (
    <div>
      <h1>Contact Us</h1>
      <p>You can reach us at [email protected].</p>
    </div>
  );
};

export default ContactPage;

That's it! Run gatsby develop, and you can now visit /, /about, and /contact in your browser. No config files, no manual routing. It just works.


2. Seamless Navigation: Using the <Link> Component 🚀

The Problem: Now that we have pages, we need to let users move between them. The old-school way is to use an HTML <a> tag: <a href="/about">About</a>. But this has a major drawback in modern web apps: clicking it causes a full page reload. The browser screen goes white for a moment, and all the site's assets are re-downloaded. It's like having to exit a building and walk back in through the front door just to go to an adjacent room. It’s slow and provides a jarring user experience.

The Solution: Gatsby's Blazing Fast <Link> Component

Gatsby provides a custom <Link> component that delivers an incredibly fast and smooth navigation experience.

Definition: The <Link> component is Gatsby's built-in way to navigate between internal pages of your site. It prevents full page reloads and uses performance optimizations to make transitions feel almost instant. For any link to an external site (e.g., your Twitter profile), you should still use a standard <a> tag.

How It Works Under the Hood (The Magic of Pre-loading):
The <Link> component is much smarter than a simple <a> tag.

  1. Intersection Observer: When a <Link> component scrolls into the user's viewport, Gatsby uses the browser's Intersection Observer API to start a low-priority pre-fetch of the linked page's resources.
  2. On Mouse Over: When the user hovers their mouse over the link, Gatsby upgrades the pre-fetch to a high-priority request, assuming a click is imminent.

By the time the user actually clicks, the next page's data is often already downloaded. This intelligent preloading is a key reason why navigating Gatsby sites feels so fast.

Hands-On Example:

Let's create a simple navigation menu and add it to our index.js page.

src/pages/index.js

javascript
import React from 'react';
// 1. Import the Link component from Gatsby
import { Link } from 'gatsby';

const HomePage = () => {
  return (
    <div>
      {/* 2. Create your navigation menu */}
      <nav>
        <Link to="/">Home</Link> | {" "}
        <Link to="/about">About</Link> | {" "}
        <Link to="/contact">Contact</Link>
      </nav>
      
      <main>
        <h1>Welcome to the Homepage!</h1>
        <p>This is the main entry point of our site.</p>
      </main>
    </div>
  );
};

export default HomePage;

Now, when you click on the "About" or "Contact" links, notice how the content changes instantly without the browser tab showing a loading spinner. That's the power of <Link>!

Pro-Tip: Active Link Styling
It's common to visually highlight the link of the page the user is currently on. <Link> makes this easy with the activeStyle or activeClassName props.

javascript
<Link 
  to="/about" 
  activeStyle={{ color: "red", textDecoration: "underline" }}
>
  About
</Link>

This will automatically apply the red color and underline style when the user is on the /about page.


3. DRY Architecture: Creating Reusable Layout Components 🏛️

The Problem: Look at the navigation menu we just built. We put it in index.js. But we want that same navigation menu on the about page, the contact page, and every other page we build. Are we going to copy and paste that <nav> block into every single page file? Absolutely not. That violates a core principle of software development: DRY (Don't Repeat Yourself). If we needed to add a new "Blog" link, we'd have to hunt down and edit every single file.

The Solution: A Shared Layout Component

We can create a single, reusable Layout component that contains all the shared UI elements (like the header, navigation, and footer).

Definition: A Layout component is a wrapper component that contains the shared UI for your site. Individual page content is then passed into this layout component as a special prop called children.

This is like having a picture frame (Layout). The frame itself is always the same, but you can put any picture (children) you want inside it. You don't build a new frame for every picture.

Hands-On Example:

First, it's a best practice to create a dedicated folder for non-page components.

  1. Create a new folder: src/components/
  2. Inside it, create a new file: src/components/Layout.js

src/components/Layout.js

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

// The { children } prop is where our page content will be injected.
const Layout = ({ children }) => {
  return (
    <div style={{ margin: `0 auto`, maxWidth: 650, padding: `2rem` }}>
      <header>
        <nav>
          <Link to="/">Home</Link> | {" "}
          <Link to="/about">About</Link> | {" "}
          <Link to="/contact">Contact</Link>
        </nav>
      </header>

      {/* Page content goes here */}
      <main>{children}</main>

      <footer>
        <p>© {new Date().getFullYear()}, Built with Gatsby</p>
      </footer>
    </div>
  );
};

export default Layout;

Now, we can go back to our pages and wrap them with this new Layout component.

src/pages/index.js (Refactored)

javascript
import React from 'react';
import Layout from '../components/Layout'; // Import the Layout component

const HomePage = () => {
  return (
    // Wrap the page-specific content in the Layout component
    <Layout>
      <h1>Welcome to the Homepage!</h1>
      <p>This is the main entry point of our site.</p>
    </Layout>
  );
};

export default HomePage;

src/pages/about.js (Refactored)

javascript
import React from 'react';
import Layout from '../components/Layout'; // Import the Layout component

const AboutPage = () => {
  return (
    <Layout>
      <h1>About Us</h1>
      <p>Here is some information about our awesome company.</p>
    </Layout>
  );
};

export default AboutPage;

Now, all our pages have a consistent header and footer. If you want to change the navigation, you only have to edit Layout.js once. This is clean, efficient, and much easier to maintain.


4. Handling the Lost User: Customizing the 404 Error Page 🗺️

The Problem: Sooner or later, a user will try to visit a page on your site that doesn't exist. Maybe they mistyped a URL or followed a broken link. By default, the web server shows a generic, often ugly, "404 Not Found" error. This breaks the user experience and makes your site look unprofessional.

The Solution: A Custom, Helpful 404 Page

Gatsby makes it incredibly easy to create your own custom 404 page, turning a moment of user frustration into a helpful, on-brand experience.

Definition: By creating a React component at src/pages/404.js, you can define a custom page that Gatsby will automatically show whenever a user requests a path that does not exist.

This is another piece of Gatsby's file-based routing magic. It specifically looks for a file named 404.js and knows to use it as the fallback for any unresolved routes.

Hands-On Example:

Let's create our custom 404 page.

src/pages/404.js

javascript
import React from 'react';
import { Link } from 'gatsby';
import Layout from '../components/Layout';

const NotFoundPage = () => {
  return (
    <Layout>
      <h1>404: Page Not Found</h1>
      <p>Oops! The page you are looking for has been moved or doesn't exist.</p>
      <p>Let's get you back home.</p>
      <Link to="/">Go to Homepage</Link>
    </Layout>
  );
};

export default NotFoundPage;

Important Note on Development:
When you're running gatsby develop, Gatsby shows its own development 404 page by default, which helpfully lists all the pages on your site. To see your custom 404 page, you'll need to click the "Preview custom 404 page" button on that screen. When you build your site for production with gatsby build, your custom 404.js will work as expected.


References for Extra Reading

Challenge

You are tasked with correctly structuring the components for a small Gatsby website within a single file. The code editor contains four component shells: Layout, HomePage, AboutPage, and NotFoundPage.

Your mission is to complete the code based on the TODO comments:

  1. Complete the Navigation: In the Layout component's <nav> element, replace the TODO comments with the correct components for navigation:

    • Use Gatsby's <Link> component to create a link to the Home page (/).
    • Use Gatsby's <Link> component to create a link to the About page (/about).
    • Use a standard <a> tag for the external link to https://www.gatsbyjs.com/.
  2. Render Page Content: In the Layout component's <main> element, ensure it correctly renders the children prop that will be passed from the page components.

  3. Apply the Layout: For HomePage, AboutPage, and NotFoundPage, wrap the existing JSX content within the Layout component to apply the site's shared structure.

Expected result

Your final code should correctly implement the four components according to the instructions.

  • The Layout component should contain two <Link> components inside its <nav> element with the to prop set to '/' and '/about' respectively.
  • The Layout component should also contain one <a> tag with the href prop set to 'https://www.gatsbyjs.com/'.
  • The Layout component must render its children prop inside the <main> element.
  • The HomePage, AboutPage, and NotFoundPage components must each return their content wrapped inside the <Layout> component. For example, HomePage should return <Layout><div>...</div></Layout>.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.