Recipes: Pages and Layouts
Add pages to your Gatsby site, and use layouts to manage common page elements.
Inside a Gatsby project, you may see some or all of the following folders and files:
Some notable files and their definitions:
gatsby-config.js— configure options for a Gatsby site, with metadata for project title, description, plugins, etc.
gatsby-node.js— implement Gatsby’s Node.js APIs to customize and extend default settings affecting the build process
gatsby-browser.js— customize and extend default settings affecting the browser, using Gatsby’s browser APIs
gatsby-ssr.js— use Gatsby’s server-side rendering APIs to customize default settings affecting server-side rendering
- For a tour of all the common folders and files, read the docs on Gatsby’s Project Structure
- For common commands, check out the Gatsby CLI docs
- Check out the Gatsby Cheat Sheet for downloadable info at a glance
Gatsby core automatically turns React components in
src/pages into pages with URLs.
For example, components at
src/pages/about.js would automatically create pages from those filenames for the site’s index page (
- Create a directory for
src/pagesif your site doesn’t already have one.
- Add a component file to the pages directory:
gatsby developto start the development server.
- Visit your new page in the browser:
Routing for links internal to your Gatsby site relies on the
<Link /> component.
- A Gatsby site with two page components:
- The Gatsby CLI to run
- Open the index page component (
src/pages/index.js) and import the
<Link />component from Gatsby. Add a
<Link />component to the JSX code and give it a
toproperty with the pathname value of
"/contact/"to output an HTML link with Gatsby powers:
gatsby developand navigate to the index page. You should have a link that takes you to the contact page when clicked!
<Link />component is a wrapper around
It’s common to wrap pages with a React layout component, which makes it possible to share markup, styles, and functionality across multiple pages.
- Create a layout component in
src/components, where child components will be passed in as props:
- Import and use the layout component in a page:
You can create pages programmatically in the
gatsby-node.js file with helper methods Gatsby provides.
- A Gatsby site
gatsby-node.js, add an export for
- Destructure the
createPageaction from the available actions so it can be called by itself, and add or get data
- Loop through the data in
gatsby-node.jsand provide the path, template, and context (data that will be passed in the props’ pageContext) to
createPagefor each invocation
- Create a React component to serve as the template for your page that was used in
gatsby developand navigate to the path of one of the pages you created (like at
http://localhost:8000/Fido) to see the data you passed it displayed on the page
- Tutorial section on programmatically creating pages from data
- Reference guide on using Gatsby without GraphQL
- Example repo for this recipe