Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically load images with react

Tags:

reactjs

I created a component that renders images

this is the component.

import React, { lazy, Suspense } from "react";

const Icon = (props) => {
    const { src } = props;

    return (
        <img src={src}  />
    );
};

export default Icon;

then I use it like this

import ExampleIcon from "./../images/icons/example.png";
...
<Icon src={ExampleIcon} />

is there a more efficient way to load the icons? and then just "load" example.png and use it as a source? tried to change it to:

const Icon = (props) => {
    const src = lazy(() => import("./../images/icons/" + props.src + ".png"));
    return (
        <Suspense fallback={<p>loading...</p>}><img src={src} /></Suspense>
    );
};

looks like it doesn´t work that way. any other ideas? thanks!

like image 445
handsome Avatar asked Oct 16 '22 00:10

handsome


1 Answers

No, you can't do this, since React.lazy() must be at the top level and only return React components. To lazily load images you can do inside an effect:

function Icon = props => {
    const [image, setImage] = useState()

    useEffect(() => {
        import("./../images/icons/" + props.src + ".png").then(setImage)
    }, [props.src])


    return image ? <img src={image} /> : 'Loading...'
}

Edit: there's one little problem with this, namely, Webpack will not be able to figure out the file to code split since the string in the import function is not a literal. You could still access files in the public directory dynamically using fetch instead. And perhaps you don't need fetch at all, just provide an url to src and spare the whole hassle.

like image 128
Mordechai Avatar answered Oct 19 '22 02:10

Mordechai