Created
October 12, 2019 22:22
-
-
Save TerribleDev/02663afb2a0a83fa7b4bb67032ea718f to your computer and use it in GitHub Desktop.
A component to render responsive images in gatsby
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
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