Part of a series on Gatsby v2
You've heard about StaticQuery as part of Gatsby v2. GraphQL everywhere. Sounds great, but how does it work?
tl;dr - Wrap any component in
StaticQueryand pass two propsqueryandrender. These queries do not get any data about the current page, they're static for the entire build.
StaticQuery?In Gatsby v1 there was only 2 places you could use GraphQL. Layouts and pages. Layouts have disappeared in Gatsby v2. Pages still use GraphQL.
Imagine you want to pass the title from you gatsby-config.js file into a component. In Gatsby v1 you would have to get that data via the layout or the page. With StaticQuery, you can get that data anywhere.
Or put another way, StaticQuery lets you write GraphQL queries which are parsed once during the build process. Think of it like this:
StaticQuery instances are parsed, their queries run, and the data bound to their componentsStaticQuery?Short answer, anywhere. You just import and it works. A few examples where StaticQuery would be useful:
Enough theory, time to dive into some code. Here's the example from the StaticQuery docs:
import React from "react"
import { StaticQuery, graphql } from "gatsby"
const Header = () => (
<StaticQuery
query={graphql`
query {
site {
siteMetadata {
title
}
}
}
`}
render={data => (
<header>
<h1>{data.site.siteMetadata.title}</h1>
</header>
)}
/>
)
export default HeaderLet's unpack that a bit.
StaticQuery from gatsby. It's a named export.<StaticQuery just like any other React componentquery and renderThe query prop takes a graphql template string
graphql must be imported from gatsby in Gatsby v2The render prop takes a function
datadata argument is filled with the result of the GraphQL queryh1 tag containing data.site.siteMetadata.titleNOTE: The
dataargument passed to therenderfunction is notprops, it is only the data. It's more likeprops.data, and it should not be destructured like({ data }) => ....
If you haven't seen it before, the siteMetadata object is filled from gatsby-config.js. It's a convenient way to pass config values into your Gatsby site without hard coding them.
If you'd like to share this post, here are some handy links to make that easier.
Post last updated: July 18, 2018
Feedback? A point to make? Express yourself via the comment form below.
Don't forget to check the captcha. Otherwise we won't receive your comment.
Be the first to post a comment on this post