Search code examples
reactjsimagedynamic-importconditional-rendering

React Dynamically Import Images


In my React code, I want to display several images in my folder. I have about 100 images and I don't want to import all of the images in different import statements. I want to import them maybe with the index of the images. The below is what I mean:

import LoadImages from './images/${index}.jpeg';

Is there any import statements like the above one?

This is an example with two images:

import React from 'react';
import './App.css';
import Image1 from './images/0.jpeg';
import Image2 from './images/1.jpeg';

const images = Array.from({ length: 2 }, (_, i) => {
  return (
    <img
      src={i === 0 ? Image1 : Image2}
      alt={i.toString()}
      key={i}
      style={{ marginBottom: '3%', marginTop: '3%' }}
    />
  );
});

export default function App() {
  return <div className='App'>{images}</div>;
}

The above code just includes 2 images. What should I do with nearly 100 images? Also, in the src part of the image component, I cannot use this structure with 100 images.

What do you advise me to do?


Solution

  • In case of loading assets like image you can load them sync via require. Assuming you use file-loader in your webpack configuration.

    The solution looks like this:

    const images = Array.from({ length: 2 }, (_, i) => {
      return (
        <img
          src={require(`./images/${i}`).default}
          alt={i.toString()}
          key={i}
          style={{ marginBottom: '3%', marginTop: '3%' }}
        />
      );
    });
    
    

    An update based on new request without knowing the name

    In case of having no idea about the file name, you can go for require.context to load what you need as following:

    const templates = require.context('./images', true, /\.(jpg|jpeg)$/);
    
    const images = templates.keys().map((elem) => (
      <img key={elem} src={templates(elem).default} />
    ))