Skip to content

Instantly share code, notes, and snippets.

@r-i-c-h
Created September 12, 2019 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-i-c-h/e01b4eac8a4f88cda55177f46c8d3275 to your computer and use it in GitHub Desktop.
Save r-i-c-h/e01b4eac8a4f88cda55177f46c8d3275 to your computer and use it in GitHub Desktop.
Gatsby Generic Image <Img> Component
// 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