Created
September 12, 2019 22:38
-
-
Save r-i-c-h/e01b4eac8a4f88cda55177f46c8d3275 to your computer and use it in GitHub Desktop.
Gatsby Generic Image <Img> Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Per https://criscodes.hashnode.dev/how-to-render-multiple-images-in-gatsby-using-image-component-cjxoowlou000pfms1o91x71ts | |
// Cycles through an array of *all* of the images and uses .find() to pass along one with a matching filename | |
// Max image width is set as 1200px, but can be changed... | |
// This component has zero styling (other than the implied max-width) | |
import React from "react" | |
import { StaticQuery, graphql } from "gatsby" | |
import Img from "gatsby-image" | |
const Image = ({filename, alt}) => ( | |
<StaticQuery | |
query={graphql` | |
query { | |
images: allFile { | |
edges { | |
node { | |
relativePath | |
name | |
childImageSharp { | |
fluid(maxWidth: 1200) { | |
...GatsbyImageSharpFluid | |
} | |
} | |
} | |
} | |
} | |
} | |
`} | |
render={data => { | |
const image = data.images.edges.find(n => { | |
return n.node.relativePath.includes(props.filename) | |
}) | |
if (!image) { | |
return null | |
} | |
const imageFluid = image.node.childImageSharp.fluid | |
return <Img alt={props.alt} fluid={imageFluid} /> | |
}} | |
/> | |
) | |
export default Image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment