Skip to content

Instantly share code, notes, and snippets.

@annedorko
Created March 12, 2022 10:22
Show Gist options
  • Save annedorko/7d8546de4add61d026a09914aea495af to your computer and use it in GitHub Desktop.
Save annedorko/7d8546de4add61d026a09914aea495af to your computer and use it in GitHub Desktop.
SVG Friendly Gatsby Image Component
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