Created
July 13, 2021 16:40
-
-
Save alexanderson1993/03ae1237188fcb74275970023fefa313 to your computer and use it in GitHub Desktop.
SVG Image Loader
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
// 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