mtyson
mtyson

Reputation: 8550

Gatsby: Define static query in JavaScript?

So in a page, you can define a query as an object in the javascript and it is automatically passed to the component as the data prop.

In components, that doesn't happen, and the examples I've seen show the query defined declaratively as part of the markup, then handed into a render method. I really don't like that at all.

What is the gatsby way to define a graphql query in the JS of a component and then consume it in that component.

For example:

  <Img fixed={data.logo.childImageSharp.fixed} />

This is a gatsby image using the graphql data object. But that object is only available on a page, not a component. (Right now I'm passing the data prop into the component from the page, but that ain't what I want)

Upvotes: 2

Views: 129

Answers (1)

ksav
ksav

Reputation: 20821

Check out useStaticQuery in the docs.

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
export default () => {
  const data = useStaticQuery(graphql`
    query HeaderQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)
  return (
    <header>
      <h1>{data.site.siteMetadata.title}</h1>
    </header>
  )
}`

Upvotes: 1

Related Questions