2

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)

2
  • Can you show where you want to use that query? Commented Feb 13, 2020 at 19:44
  • @ZohaibIjaz added Commented Feb 13, 2020 at 23:03

1 Answer 1

1

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>
  )
}`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.