Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Created July 13, 2021 16:40
Show Gist options
  • Save alexanderson1993/03ae1237188fcb74275970023fefa313 to your computer and use it in GitHub Desktop.
Save alexanderson1993/03ae1237188fcb74275970023fefa313 to your computer and use it in GitHub Desktop.
SVG Image Loader
// This is a React component that loads and inlines an SVG image, making it easier to style
// with CSS. It renders an <img> first, and then renders the inline SVG once it's been loaded.
import {useState, useEffect, memo, ComponentPropsWithoutRef} from "react";
export const SVGImageLoader: React.FC<
{url: string} & ComponentPropsWithoutRef<"img">
> = memo(({url, alt, ...props}) => {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
async function loadSvg() {
const res = await fetch(url);
if (!res.ok) return;
const data = await res.text();
if (data.includes("<svg")) {
setData(data);
}
}
if (url.endsWith(".svg")) {
loadSvg();
}
}, [url]);
if (data) {
return (
<div role="img" {...props} dangerouslySetInnerHTML={{__html: data}} />
);
}
return <img draggable="false" alt={alt} aria-hidden {...props} src={url} />;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment