Webinar

“Digging into Gatsby 5’s Slice API” Register now

Building with Components

To use Gatsby, you will need a basic understanding of React components.

The official React tutorial is a good place to start.

Why React components?

React’s component architecture simplifies building large websites by encouraging modularity, reusability, and clear abstractions. React has a large ecosystem of open source components, tutorials, and tooling that can be used seamlessly for building sites with Gatsby. Gatsby is built to behave almost exactly like a normal React application.

The following model shows how data from a source can be queried by GraphQL for use inside components in the process of building a Gatsby site:

src/pages/homepage.js
export ({ data }) => (
  <div>
    <h1>{data.site.title}</h1>
    {data.site.description}
  </div>
)

React powers components in Gatsby sites that are rehydrated, whatever you can do in React you can do with Gatsby.

Your components can pull in whatever data they need from any source in the data layer.

Thinking in React is a good resource for learning how to structure applications with React.

How does Gatsby use React Components?

Everything in Gatsby is built using components.

A basic directory structure of a project might look like this:

Page components

Components under src/pages become pages automatically with paths based on their file name. For example src/pages/index.jsx is mapped to yoursite.com and src/pages/about.jsx becomes yoursite.com/about/. Every .js, .jsx, or .tsx file in the pages directory must resolve to a React component, otherwise your build will fail.

Example:

Page template components

You can programmatically create pages using “page template components”. All pages are React components but very often these components are just wrappers around data from files or other sources.

src/templates/post.jsx is an example of a page template. It queries GraphQL for markdown data (sourcing from the posts directory) and then renders the page using this data.

See part six of the tutorial for a detailed introduction to programmatically creating pages.

Example:

Non-page components

A non-page component is one that’s embedded inside some other component, forming a component hierarchy. An example would be a SEO component that’s included in multiple page components. Gatsby uses GraphQL to enable components to declare the data they need. Using the useStaticQuery hook, you can colocate a non-page component with its data. In the example above that would be the src/components/seo.jsx component. Here’s a guide on how to create a SEO component.

Edit this page on GitHub
© 2022 Gatsby, Inc.