logo
eng-flag

Gatsby Cheatsheet

Table of Contents

  1. Installation and Setup
  2. Project Structure
  3. Pages and Routing
  4. Components
  5. GraphQL Queries
  6. Images and Assets
  7. Styling
  8. Plugins
  9. Data Fetching
  10. SEO and Head
  11. Deployment

Installation and Setup

Install Gatsby CLI

npm install -g gatsby-cli

Create a new Gatsby project

gatsby new my-gatsby-site
cd my-gatsby-site

Run development server

gatsby develop

Build for production

gatsby build

Serve production build locally

gatsby serve

Project Structure

  • /src: Source code
    • /pages: React components for pages
    • /components: Reusable React components
    • /templates: Templates for programmatically created pages
    • /styles: CSS files
  • /static: Static assets that will be copied to the public folder
  • /gatsby-config.js: Gatsby configuration file
  • /gatsby-node.js: Gatsby Node.js APIs
  • /gatsby-browser.js: Gatsby browser APIs
  • /gatsby-ssr.js: Gatsby server-side rendering APIs

Pages and Routing

Creating a page

// src/pages/about.js
import React from 'react'

const AboutPage = () => (
  <div>
    <h1>About Us</h1>
    <p>This is the about page</p>
  </div>
)

export default AboutPage
import { Link } from 'gatsby'

const Navigation = () => (
  <nav>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>
  </nav>
)

Programmatic page creation

// gatsby-node.js
exports.createPages = async ({ actions }) => {
  const { createPage } = actions
  createPage({
    path: "/using-dsg",
    component: path.resolve(`src/templates/using-dsg.js`),
    context: {},
    defer: true,
  })
}

Components

Functional component

import React from 'react'

const Header = ({ title }) => (
  <header>
    <h1>{title}</h1>
  </header>
)

export default Header

Class component

import React, { Component } from 'react'

class Counter extends Component {
  state = { count: 0 }

  increment = () => {
    this.setState(prevState => ({ count: prevState.count + 1 }))
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    )
  }
}

export default Counter

GraphQL Queries

Page query

import React from 'react'
import { graphql } from 'gatsby'

const IndexPage = ({ data }) => (
  <div>
    <h1>{data.site.siteMetadata.title}</h1>
  </div>
)

export const query = graphql`
  query HomePageQuery {
    site {
      siteMetadata {
        title
      }
    }
  }
`

export default IndexPage

Static query (useStaticQuery hook)

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

const SiteInfo = () => {
  const data = useStaticQuery(graphql`
    query SiteInfoQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `)

  return (
    <div>
      <h1>{data.site.siteMetadata.title}</h1>
      <p>{data.site.siteMetadata.description}</p>
    </div>
  )
}

export default SiteInfo

Images and Assets

Using gatsby-image

import React from 'react'
import { graphql, useStaticQuery } from 'gatsby'
import Img from 'gatsby-image'

const Image = () => {
  const data = useStaticQuery(graphql`
    query {
      file(relativePath: { eq: "example.jpg" }) {
        childImageSharp {
          fluid(maxWidth: 800) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

  return <Img fluid={data.file.childImageSharp.fluid} alt="Example" />
}

export default Image

Using static folder

import React from 'react'

const StaticImage = () => (
  <img src="/logo.png" alt="Logo" />
)

export default StaticImage

Styling

CSS Modules

import React from 'react'
import styles from './button.module.css'

const Button = ({ children }) => (
  <button className={styles.button}>{children}</button>
)

export default Button

Styled Components

import React from 'react'
import styled from 'styled-components'

const StyledButton = styled.button`
  background-color: #0077b5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
`

const Button = ({ children }) => (
  <StyledButton>{children}</StyledButton>
)

export default Button

Plugins

Installing and configuring a plugin

// gatsby-config.js
module.exports = {
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
  ],
}

Data Fetching

Fetching data at build time

// gatsby-node.js
const fetch = require('node-fetch')

exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
  const { createNode } = actions

  const response = await fetch('https://api.example.com/data')
  const data = await response.json()

  data.forEach(item => {
    const node = {
      ...item,
      id: createNodeId(`example-${item.id}`),
      internal: {
        type: 'ExampleItem',
        contentDigest: createContentDigest(item),
      },
    }
    createNode(node)
  })
}

Fetching data at runtime

import React, { useState, useEffect } from 'react'

const RuntimeData = () => {
  const [data, setData] = useState(null)

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data')
      const result = await response.json()
      setData(result)
    }
    fetchData()
  }, [])

  if (!data) return <div>Loading...</div>

  return (
    <div>
      <h1>Runtime Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

export default RuntimeData

SEO and Head

Using react-helmet

import React from 'react'
import { Helmet } from 'react-helmet'

const SEO = ({ title, description }) => (
  <Helmet>
    <title>{title}</title>
    <meta name="description" content={description} />
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    <meta name="twitter:card" content="summary_large_image" />
  </Helmet>
)

export default SEO

Deployment

Deploying to Netlify

  1. Push your Gatsby project to a GitHub repository
  2. Log in to Netlify and click "New site from Git"
  3. Choose GitHub and select your repository
  4. Set build command to gatsby build
  5. Set publish directory to public/
  6. Click "Deploy site"

Deploying to Gatsby Cloud

  1. Log in to Gatsby Cloud
  2. Click "Add a site"
  3. Connect your GitHub repository
  4. Configure build settings if necessary
  5. Click "Create site"

2024 © All rights reserved - buraxta.com