Search code examples
reactjsgatsbyprismic.iogatsby-image

How do I query for gatsby-image?


I am trying to query a prismic single type to display photos via gatsby-image. After messing around in GraphiQL, I see the image url but I'm not sure how to plug it in to gatsby-image. Any advice? enter image description here

  <Layout 
    location={`home`}
    image={data.prismic._allDocuments.edges.node.hero_image.childImageSharp.fluid}
  >

Solution

  • Anytime you see the prefix all in GraphQL you should assume that it will return an array of things.

    In GraphQL we can see that _allDocuments.edges returns an array of edges. If we want to display everything in that array, we need to map over it.

    If we know the index of the single thing we want, we can access it directly with bracket notation.

    // ./pages/index.js
    
    import React from "react"
    import Layout from "../components/layout"
    
    
    const IndexPage = ({data}) => {
      return (
      <Layout>
        <ul>
          {data.allFile.edges.map((edge) => (
            <li>{edge.node.name}</li>
          ))}
        </ul>
      </Layout>
    )}
    
    export default IndexPage
    
    
    export const query = graphql`
      query HomePageQuery {
        allFile(filter: {relativePath: {regex: "/png$/"}}) {
          edges {
            node {
              id
              name
              relativePath
              publicURL
              childImageSharp {
                fixed(width: 111) { 
                  ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }
    `
    

    Then you can just import Img from "gatsby-image" and pass the relevant queried value to the <Img /> component's fixed or fluid prop.

    // ./pages/index.js
    
    import React from "react"
    import Layout from "../components/layout"
    import Img from "gatsby-image"
    
    
    const IndexPage = ({data}) => {
      return (
      <Layout>
          {data.allFile.edges.map((edge) => (
            <Img fixed={edge.node.childImageSharp.fixed} />
          ))}
      </Layout>
    )}
    
    export default IndexPage
    
    
    
    export const query = graphql`
      query HomePageQuery {
        allFile(filter: {relativePath: {regex: "/png$/"}}) {
          edges {
            node {
              id
              name
              relativePath
              publicURL
              childImageSharp {
                fixed(width: 111) { 
                  ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }
    `