I’m a beginner on Gatsby. I try to display a batch of images in grid from a specific folder. I find a script to do that, but that’s catch all pics from my data
folder and my purpose is target a specific one. I try a script but that’s don’t work with allImageSharp
when I try to filter this one allImageSharp(filter: { sourceInstanceName: { eq: "media" } }) {
.
When I try allImageSharp(filter: { id: { regex: "/media/" } }) {
just display a blank window, but that’s work fine like that allImageSharp {
javascript
import React from "react" import { graphql } from "gatsby" import Img from "gatsby-image" import Layout from "../components/layout" const img_grid_style = { display: "grid", gridTemplateColumns: `repeat(auto-fill, 200px)`, } export default ({ data }) => ( <div> <Layout title="IMAGE GRID"></Layout> <div style={img_grid_style}> {data.allImageSharp.edges.map(edge => ( <Img fluid={edge.node.fluid} /> ))} </div> </div> ) export const query = graphql` query { allImageSharp(filter: { sourceInstanceName: { eq: "media" } }) { edges { node { id fluid(maxWidth: 200, maxHeight: 200) { ...GatsbyImageSharpFluid } } } } } `
config
module.exports = { plugins: [ `gatsby-transformer-sharp`, { resolve: `gatsby-plugin-sharp`, options: { // Available options and their defaults: base64Width: 20, // forceBase64Format: ``, // valid formats: png,jpg,webp // don't work on OSX useMozJpeg: process.env.GATSBY_JPEG_ENCODER === `MOZJPEG`, stripMetadata: true, defaultQuality: 50, failOnError: true, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `media`, path: `./media/`, }, }, ], }
Advertisement
Answer
Change your path in your gatsby-source-filesystem
to:
{ resolve: `gatsby-source-filesystem`, options: { name: `media`, path: `${__dirname}/media/`, }, },
The snippet above will match. rootOfYourProject/media
, change it to your media path keeping the ${__dirname}
.
Now, your filesystem can be filtered by media
(without slashes).
export const query = graphql` { allFile(filter: {sourceInstanceName: {eq: "media"}}) { nodes { childImageSharp { fluid { base64 tracedSVG srcWebp srcSetWebp originalImg originalName } } } } } `
Since you can’t use fragments in the GraphQL playground (localhost:8000/___graphql
) I’ve used the extended version, however, you should use the ...GatsbyImageSharpFluid
once applied to your code.
allFile
or allImageSharp
should do the trick.
I’ve fixed your project in this PR. The query was retrieving properly the results, however, you were missing some nested objects to get the final fluid image:
export default ({ data }) => { return <div> <Layout title="IMAGE GRID FROM SPECIFIC FOLDER"></Layout> <div style={img_grid_style}> {data.allFile.edges.map(({ node }) => ( <Img fluid={node.childImageSharp.fluid} /> ))} </div> </div> }