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.
Creating Pages from Data Programmatically
We can create pages from data programmatically with Gatsby.
For example, we can write:
gatsby-config.js
module.exports = {
plugins: [
`gatsby-transformer-remark`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `content`,
path: `${__dirname}/src/content`,
},
},
],
siteMetadata: {
title: "My Homepage",
description: "This is where I write my thoughts.",
},
}
src/content/post.md
---
title: My First Post
date: 2019-07-10
path: /my-first-post
---
This is my first Gatsby post written in Markdown!
gatsby-node.js
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` })
createNodeField({
node,
name: `slug`,
value: slug,
})
}
}
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`)
data.allMarkdownRemark.edges.forEach(edge => {
const slug = edge.node.fields.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/post.js`),
context: { slug },
})
})
}
src/templates/post.js
import React from "react"
import { graphql } from "gatsby"
export default function BlogPost({ data }) {
const post = data.markdownRemark
return (
<div>
<h1>{post.frontmatter.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
)
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`
First, we add the gatsby-transformer-remark
and gatsby-source-filesystem
plugins to read Markdown files and parse them to HTML.
We create the slug
field with the createNode
function.
We call createNodeField
to create our slug.
With the if
statement in onCreateNode
, we only add the slug
field if we query for MarkdownRemark
entries.
Then in the createPages
function, we make the query for the slug and then loop through each entry with forEach
.
In the forEach
callback, we call actions.createPage
to add the pages from the entries returned.
path
is set to the slug
,
component
is set to the template file location.
context
has the data we want to display in the template.
In post.js
, we make the query for the post with the given slug.
Then we get the data from the data
prop and render it in our JSX.
Now when we go to http://localhost:8000/post, we see:
My First Post
This is my first Gatsby post written in Markdown!
displayed.
Conclusion
We can create pages from data programmatically with Gatsby.
This way, we can create our pages from Markdown files and render them.