Created
March 12, 2022 10:22
-
-
Save annedorko/7d8546de4add61d026a09914aea495af to your computer and use it in GitHub Desktop.
SVG Friendly Gatsby Image 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
import React from "react"; | |
import {StaticQuery, graphql} from "gatsby"; | |
import {GatsbyImage} from "gatsby-plugin-image"; | |
export const Image = props => ( | |
<StaticQuery | |
query={graphql` | |
query { | |
images: allFile { | |
edges { | |
node { | |
relativePath | |
publicURL | |
name | |
childImageSharp { | |
gatsbyImageData(layout: FULL_WIDTH) | |
} | |
} | |
} | |
} | |
} | |
`} | |
render={data => { | |
const image = data.images.edges.find(n => { | |
const file = n.node.relativePath.replace(/\.[^/.]+$/, ""); | |
const path = props.filename.replace(/\.[^/.]+$/, ""); | |
return path.includes(file); | |
}); | |
if (!image) { | |
return null; | |
} | |
var relativePath = image.node.relativePath; | |
var ext = relativePath.substring(relativePath.lastIndexOf(".") + 1); | |
if ("svg" !== ext) { | |
var imagePath = image.node.childImageSharp.gatsbyImageData; | |
return <GatsbyImage alt={props.alt} image={imagePath} />; | |
} else { | |
var imagePath = image.node.publicURL; | |
return <img alt={props.alt} src={imagePath} />; | |
} | |
}} | |
/> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment