reactjs – dynamically load images with react

reactjs – dynamically load images with react

No, you cant 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: theres 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 dont need fetch at all, just provide an url to src and spare the whole hassle.

You could apply this approach:
Preloading images with JavaScript

const img=new Image();

And how to do it with a hook with an online example:

Another approach just using hooks:

import React, { useEffect } from react;
import ./styles.css;

const loadImg = (src: string): Promise<string> =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    img.onload = () => resolve(src);
    img.onerror = () => reject(new Error(could not load image));

export default function App() {
  const [src, setSrc] = React.useState(preloadimg);
  useEffect(() => {
    const load = async () => {
      await loadImg(
      ).then((src) => {
    }; // Execute the created function directly
  }, [src, setSrc]);

  return (
    <div className=App>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <img src={src} alt=example />

reactjs – dynamically load images with react

Leave a Reply

Your email address will not be published.