简体   繁体   中英

Gatsby / Graphql - Can't display img from query

Below is my code:

import React from 'react'
import { graphql, useStaticQuery } from "gatsby"
import Img from 'gatsby-image'


const ImageGallery = () => {


const data = useStaticQuery(graphql`
query {
  images: allFile(filter: { sourceInstanceName: {eq: "images" }}) {
    edges {
      node {
        relativePath
        childImageSharp {
          id
          fluid {
            originalImg
          }
        }
      }
    }
  }
}
`)

 // Filters all the images from "gallery-one"

 const galleryImages = data.images.edges.filter(edge => 
  edge.node.relativePath.startsWith("gallery-one")
 )

console.log(data)
console.log(galleryImages)


    return (
        <div>
            <h1>Gallery One</h1>
            {
             // Mapping over galleryImages array to display each image

              galleryImages.map((image) =>
                <div>
                // Returns relative path for each image
                {image.node.childImageSharp.fluid.originalImg}
                 // Returns nothing
                <Img fluid={image.node.childImageSharp.fluid.originalImg} />
                </div>
              )
            }
        </div>
    )
}


export default ImageGallery

With the first part in the map, it returns:

/static/3608211e3ce3f78486c9e344b92332d9/5f7bf/20171107_155145.jpg

/static/fccd9cdb1c9b525bfaf9282343d680a6/5f7bf/20171101_103124.jpg

/static/cdcbaebc030e210debc70bdff7a8d539/5f7bf/20171107_155126.jpg

/static/ef8708d7f536bd152c9ce98833d6d871/5f7bf/20171101_103218.jpg

/static/1c3b4e40cb5044e604009935b625fa38/5f7bf/20171101_103138.jpg

One for each image in the 'gallery-one' folder, but I cannot figure out how to get it to display using Gatsby Img.

I feel like this is really close, but I can't seem to figure it out

fluid={image.node.childImageSharp.fluid.originalImg}

Yes, you're almost there.

When you query an image to be displayed using gatsby-image you have 2 options:

  • Use a GraphQL fragment:

    Instead of using originalImg you should use ...GatsbyImageSharpFluid which will provide to the fluid object all information required.

  • Querying all the data required. In this case you should use:

     fluid (maxWidth: 800) { aspectRatio src srcSet sizes originalImg originalName }

    Disclaimer: the default maxWidth is 800px . If you don't set it, it will take the default value.

Once you gathered all the information, it needs to be passed to <Img> removing your originalImg , such as:

fluid={image.node.childImageSharp.fluid}

For further information check Gatsby Image API documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM