I am working on an issue where SVG image needs to be loaded from URL(AWS S3) to a react component. I am able to successfully show and load image using the SVG-inline react component from a local file. However, the svg files needs to be loaded inline from S3 bucket, JS svg import does not work with URLs.
So I am trying to find the best alternative solution for this?
SVGs are scalable, fully customizable, lightweight, and easy to animate image formats. You can use SVGs as an icon, logo, image, or backdrop image in your react application.
@ivnkld answer pointed me to the right direction, thanks! And for Googlers such as I was, here is implementation of the same approach with hooks:
import React, { useEffect, useState } from 'react';
const SvgInline = props => {
const [svg, setSvg] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [isErrored, setIsErrored] = useState(false);
useEffect(() => {
fetch(props.url)
.then(res => res.text())
.then(setSvg)
.catch(setIsErrored)
.then(() => setIsLoaded(true))
}, [props.url]);
return (
<div
className={`svgInline svgInline--${isLoaded ? 'loaded' : 'loading'} ${isErrored ? 'svgInline--errored' : ''}`}
dangerouslySetInnerHTML={{ __html: svg }}
/>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With