Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying all images in folder using GraphQL

I am currently learning Gatsby.js and GraphQL as a supplementary technology and got stuck with querying. I want to query all images from a folder, map trough them and display them in a react component as a grid. I am using gatsby-source-filesystem but can't figure out, how to address specifically that folder and get all images from it.

My plugin set up for source-filesystem looks like this.

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/src/posts`,
    name: 'posts',
  },
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/assets/images`,
  },
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `photos`,
    path: `${__dirname}/src/assets/photos`,
  },
},

I have my images in src/assets/photos

Thanks for any help!

like image 760
Dimitry Ivashchuk Avatar asked Jul 15 '18 15:07

Dimitry Ivashchuk


2 Answers

You can select specific folders using filters in graphql.

Try something like this:

query AssetsPhotos {
  allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, relativeDirectory: {eq: "photos"}}) {
    edges {
      node {
        id
        name
      }
    }
  }
}

Where eq: photos should be changed to the relative directory result you get for the files you want to target when you go to GraphiQL and run a query on allFile.

like image 60
giraffesyo Avatar answered Nov 08 '22 19:11

giraffesyo


I like to use sourceInstanceName when using gatsby-source-filesystem plugin as documented in the plugin docs.

Your gatsby-config.js

{
  resolve: "gatsby-source-filesystem",
  options: {
    path: `${__dirname}/content/legal`,
    name: "legal", // IMPORTANT: the name of your source instance
  },
}, {
  resolve: "gatsby-source-filesystem",
  options: {
    path: `${__dirname}/content/blog`,
    name: "blog",
  },
}

Then you can directly address them in your GraphQL query using filter and sourceInstanceName:

export const query = graphql`
{
  allFile(filter: {
      extension: {eq: "png"},
      sourceInstanceName: {eq: "blog"}
    })
  {
    edges {
      node {
      childImageSharp {
          fluid(maxWidth: 300, quality: 50) {
            originalName
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

In contrast to relativeDirectory, this way you never have to deal with changing relative paths you might refactor your project or whatever. Just let GraphQL handle it for you!

like image 12
EliteRaceElephant Avatar answered Nov 08 '22 19:11

EliteRaceElephant