简体   繁体   中英

mapping images with gatsby-image

trying to map images from a folder in a gatsby project. I set up the query in a way I thought would work based on guides I've seen. I do not get any errors and the site loads, but the images do not show up. Any thoughts? Thanks!

gatsby-config.js:

  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },

query:

    const data = useStaticQuery(graphql`
      query {
        allFile(filter:{extension:{regex:"/social/"}}) {
          edges {
            node {
              childImageSharp {
                fixed(width: 150, height: 150) {
                    ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }

    `)

return:

            <div className='socialPhotos'>
                {data.allFile.edges.map(node => 
                    <Img 
                      key={node.id}
                      title="Photo image"
                      alt="Photo"
                      fixed={node.childImageSharp.fixed}
                    />
                    )}
            </div>

The filter in your graphQL query might be the problem. Did you try your query in graphiQL in the browser?

Because you define images in your gatsby-config.js , I would suggest filtering with sourceInstanceName :

    const data = useStaticQuery(graphql`
      query {
      allFile(filter: {sourceInstanceName: {eq: "images"}}) {
          edges {
            node {
              childImageSharp {
                fixed(width: 150, height: 150) {
                    ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }
    `)

Paste your query into GraphiQL in your browser and test if you get data back: http://localhost:8000/___graphql

EDIT

This is how you can get one image from your query inside your component

const YourComponent = (props) => {
  const { data: { allFile: { edges } } } = props;
  const oneImage = edges.filter(
    el => el.node.childImageSharp.fixed.originalName === "yourImageFileName.png")
    [0].node.childImageSharp.fixed;
  // ...

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