How do I query multiple images with gatsby-image?

后端 未结 4 1812
遥遥无期
遥遥无期 2021-02-05 19:05

I have 16 images that I want to render out onto a website in a grid format.

I\'m using the following plugins for this:

  • gatsby-image
  • <
4条回答
  •  滥情空心
    2021-02-05 19:52

    Having a poke around in GraphiQL should help you, especially the Explorer. Although remember that Gatsby fragments won't work in GraphiQL.

    {
      allImageSharp {
        edges {
          node {
            id
            fluid(maxWidth: 200, maxHeight: 200) {
                ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
    

    So the above should be equal to something like the following query which will work in GraphiQL

    {
      allImageSharp {
        edges {
          node {
            id
            fluid(maxHeight: 200, maxWidth: 200) {
              src
              srcSet
              base64
              aspectRatio
              originalImg
              sizes        
            }
          }
        }
      }
    }
    

    Then your component can use this same query and render the results like this:

    import React from "react"
    import { graphql } from "gatsby"
    import Img from "gatsby-image"
    
    const imgGridStyle = {
      display: 'grid',
      gridTemplateColumns: `repeat(auto-fill, 200px)`
    };
    
    export default ({ data }) => (
      

    Hello gatsby-image

    {data.allImageSharp.edges.map(edge => )}
    ) export const query = graphql` query { allImageSharp { edges { node { id fluid(maxWidth: 200, maxHeight: 200) { ...GatsbyImageSharpFluid } } } } } `

    You can easily loop over the resulting array of imageSharp nodes returned from the query in data.allImageSharp.edges.map. Then pass each node's fluid property, as the fluid prop to gatsby-image.

    Note: This renders every imageSharp node in your project, which may or may not be what you want to achieve.


    To filter the query by folder name, you could adjust the query like this:

    {
      allImageSharp(filter: {fileAbsolutePath: {regex: "/(myFolder)/"  }}) {
        edges {
          node {
            id
            fluid(maxWidth: 200, maxHeight: 200) {
                ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
    

    Have a look at the gatsby graphql reference for filter as to how you might perform other kinds of filters on the query.

提交回复
热议问题