Gatsby

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

gatsby-ssr.js Jump to heading

The APIs wrapPageElement and wrapRootElement exist in both the SSR and browser APIs. If you use one of them, consider if you should implement it in both gatsby-ssr.js and gatsby-browser.js so that pages generated through SSR with Node.js are the same after being hydrated with browser JavaScript.

wrapRootElement Jump to heading

This is where Providers would be setup, think Redux etc

// gatsby-browser.js
const React = require('react')
const { Provider } = require('react-redux')

const createStore = require('./src/state/createStore')
const store = createStore()

exports.wrapRootElement = ({ element }) => {
return <Provider store={store}>{element}</Provider>
}

More info here

https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr

onRenderBody Jump to heading

export const onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
/**
* Preload font assets and via SSR to prevent FLOUT (Flash of Unstyled Text)
*/

<link
key="Font-Preload--Venti-Bold"
rel="preload"
href="/fonts/stage-1/VentiCF-Bold--stage1.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>,
])
}

GraphQL Jump to heading

Group deeply nested fields together Jump to heading

import { graphql, useStaticQuery } from 'gatsby'

export const useAllTags = () => {
const data = useStaticQuery(graphql`
{
allMdx {
tags: group(field: frontmatter___tags) {
tag: fieldValue
totalCount
}
}
}
`
)

return data
}

Output Jump to heading

{
"data": {
"allMdx": {
"tags": [
{
"tag": "css",
"totalCount": 4
},
{
"tag": "devops",
"totalCount": 1
},
{
"tag": "git",
"totalCount": 1
},
{
"tag": "graphql",
"totalCount": 1
}
]
}
}
}

Graphql untagged Jump to heading

Given frontmatter like this:

---
title: Gatsby
tags:
- react
- graphql
---

or this

---
title: Gatsby
---

Then query for items that don’t have tags set

query MyQuery {
allMdx(filter: { frontmatter: { tags: { eq: null } } }) {
edges {
node {
id
frontmatter {
title
tags
}
}
}
}
}

Misc Jump to heading

SEO component

Schema.org component


← Back home