Categories
Gatsby.js

Gatsby.js — Conditional Queries and Create Pages

Spread the love

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Conditionals

We can add conditional operations with our GraphQL queries.

For example, we can with:

query GetBlogPosts($withDate: Boolean = false) {
  allMarkdownRemark(limit: 3, skip: 1) {
    edges {
      node {
        frontmatter {
          title
          date @include(if: $withDate)
        }
      }
    }
  }
}

We use the $withDate boolean value in our if operator.

Creating and Modifying Pages

We can use GraphQL queries to create pages in the gatsby-node.js file.

For example, we can write:

gatsby-node.js

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions
  const result = await graphql(
    `
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              frontmatter {
                path
              }
            }
          }
        }
      }
    `
  )
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const blogPostTemplate = path.resolve(`src/templates/post.js`)
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    const path = node.frontmatter.path
    createPage({
      path,
      component: blogPostTemplate,
      context: {
        pagePath: path,
      },
    })
  })
}

gatsby-config.js

module.exports = {
  plugins: [
    `gatsby-transformer-remark`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `content`,
        path: `${__dirname}/src/content`,
      },
    },
  ]
}

src/templates/post.js

import React from "react"
import { graphql } from "gatsby"
export default function Template({ data }) {
  const { markdownRemark } = data
  const { frontmatter, html } = markdownRemark
  return (
    <div className="blog-post">
      <h1>{frontmatter.title}</h1>
      <h2>{frontmatter.date}</h2>
      <div
        className="blog-post-content"
        dangerouslySetInnerHTML={{ __html: html }}
      />
    </div>
  )
}
export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
      }
    }
  }
`

We get the results with the createPages function in gatsby-node.js .

Then we loop through the items with the forEach call and call createPage to create the posts.

We reference post.js , which is the template component.

And then we call createPage and set the template as the component.

context has data we want to display on our page.

We access that in the data prop of the Template component.

Removing Trailing Slashes

We can remove trailing slashes from the path when we create the page.

For instance, we can write:

const replacePath = path => (path === `/` ? path : path.replace(//$/, ``))

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage, deletePage } = actions
  const result = await graphql(
    `
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              frontmatter {
                path
              }
            }
          }
        }
      }
    `
  )
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const blogPostTemplate = path.resolve(`src/templates/post.js`)
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    const path = node.frontmatter.path
    const page = {
      path,
      component: blogPostTemplate,
      context: {
        pagePath: path,
      },
    }
    const oldPage = Object.assign({}, page)
    page.path = replacePath(page.path)
    if (page.path !== oldPage.path) {
      deletePage(oldPage)
      createPage(page)
    }
  })
}

We check if the oldPage.path is equal to page.path .

If they aren’t equal, then we call deletePage to delete the old page and call createPage to add the new page.

Conclusion

We can make conditional queries and create pages from GraphQL queries with Gatsby.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *