Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Import SVG inline from URL

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?

like image 241
Mikko Lasso Avatar asked Oct 24 '18 09:10

Mikko Lasso


People also ask

Does react work with SVG?

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.


1 Answers

@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 }}
        />
    );
}
like image 198
Petr Cibulka Avatar answered Oct 10 '22 21:10

Petr Cibulka