Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Created October 12, 2019 22:22
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 TerribleDev/02663afb2a0a83fa7b4bb67032ea718f to your computer and use it in GitHub Desktop.
Save TerribleDev/02663afb2a0a83fa7b4bb67032ea718f to your computer and use it in GitHub Desktop.
A component to render responsive images in gatsby
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
const Image = ({ imgName }) => {
const data = useStaticQuery(graphql`
query images {
allFile(filter: { sourceInstanceName: { eq: "images" } }) {
nodes {
name
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
}
}
`)
if (!imgName) {
return
}
const img = data.allFile.nodes.find(i => i.name === imgName)
if (!img) {
throw new Error(`Cannot find ${imgName}`)
}
return <Img fluid={img.childImageSharp.fluid} />
}
export default Image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment