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!
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.
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