Search code examples
javascriptreactjsgatsbygraphiql

How to pass Data from graphicQL to React component with gatsby?


I am trying to pass the Images through GraphicQL to my Banner component, which is a fragment component.. This code worked in my index.js but does not work when i try to create a new component.

I tried with class componennt aswell but same result

import React from 'react';
import Img from 'gatsby-image';
import { graphql } from 'gatsby'

const Banner = ({ data }) => (
    <div className="imageContainer">
         {console.log(data)}
            <Img fluid={data.image1.childImageSharp.fluid}/>
            <Img fluid={data.image2.childImageSharp.fluid}/>
            <Img fluid={data.image3.childImageSharp.fluid}/> 
    </div>
)

export const bannerImg = graphql`
   fragment bannerImg on File {
    childImageSharp {
      fluid{
        ...GatsbyImageSharpFluid
      }
    }
  }
`

export const query = graphql`
query {
    image1: file(relativePath: { eq: "images/one.jpg" }){
      ...bannerImg
    }

    image2: file(relativePath: { eq: "images/two.jpg" }){
      ...bannerImg
    }

    image3: file(relativePath: { eq: "images/three.jpg" }){
      ...bannerImg
    }
  }
`

export default Banner;

I expected something get pass as props but the component doesnt receive anything


Solution

  • Check the docs for StaticQuery

    import React from 'react'
    import { StaticQuery, graphql } from 'gatsby'
    import Img from 'gatsby-image'
    
    export const bannerImg = graphql`
       fragment bannerImg on File {
        childImageSharp {
          fluid{
            ...GatsbyImageSharpFluid
          }
        }
      }
    `
    
    const Banner () => (
      <StaticQuery
        query={graphql`
          query BannerQuery {
            image1: file(relativePath: { eq: "images/one.jpg" }){
              ...bannerImg
            }
    
            image2: file(relativePath: { eq: "images/two.jpg" }){
              ...bannerImg
            }
    
            image3: file(relativePath: { eq: "images/three.jpg" }){
              ...bannerImg
            }
          }
        `}
        render={data => (
          <div className="imageContainer">
            <Img fluid={data.image1.childImageSharp.fluid}/>
            <Img fluid={data.image2.childImageSharp.fluid}/>
            <Img fluid={data.image3.childImageSharp.fluid}/> 
          </div>
        )}
      />
    )
    
    export default Banner