2

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?

Utku Demir
  • 373
  • 1
  • 6
  • 14

2 Answers2

2

You can put your images in public folder, or a s3 bucket etc.

In the CRA docs under "When to Use the public Folder" title; its recommended if "You have thousands of images and need to dynamically reference their paths."

Then you can do something like this;

new Array(15)
  .fill(1)
  .map((_, i) => ({
    <img
      src={"/public/images/" + i + ".jpeg" }
      key={i}
      className="img-fluid"
    />
  }))

Small note: Array(15).fill(1) is basically means create 15 elements array and just put 1 into them. Since we cant do for loops inside jsx, we create an array with 15(or what number you want) elements and map through them.

Emre A
  • 240
  • 1
  • 6
  • Hi Emre, thank you for your comment. Does the number 15 specifies the length of the array? For example, if I do not know the number of images, (let's say, I upload these images to storage via my code, without knowing the number of images. I want to check these images from a cloud storage) how can I handle this case, do you have any idea? – Utku Demir Jan 15 '21 at 14:47
  • Sorry, i should've been more clear. Array(15).fill(1) is basically means create 15 elements array and just put 1 into them. Since we cant do for loops inside jsx, we create an array with 15(or what number you want) elements and map through them. About your other question; if our react app is client side, not using framework like nextjs, we cant reach filesystem in our computer or server. We have to know elements of array to map through them. You can check it on your backend and return an array of image elements with their URLs from your api, then same like casual api call response, map them. – Emre A Jan 15 '21 at 15:28
  • If you are using something like s3; i believe they have api responses that tells you how many images in your bucket's folder with their URLs. If you have your own backend, same can be done, create an endpoint that returns your files and their URLs. – Emre A Jan 15 '21 at 15:31
2

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} />
))
tmhao2005
  • 14,776
  • 2
  • 37
  • 44
  • How can I add file-loader to the webpack configuration? I do not use ant additional configuration for webpack. All the configurations come from create-react-app. – Utku Demir Jan 15 '21 at 14:37
  • Also, I want to ask a question. If I do not know the number of images, how can I write the code for this situation? – Utku Demir Jan 15 '21 at 15:04
  • If you use CRA, it's been set up for you already so you just simply use the code without configuring anything. – tmhao2005 Jan 15 '21 at 15:09
  • I dropped you another suggestion how to load images in webpack without knowing the filename – tmhao2005 Jan 15 '21 at 15:20
  • I am very happy with your additional explanations. Possibly, your additional explanation solves my problem with indefinite number of images case. I'll try these codes in my app, and I'll add my comment here. – Utku Demir Jan 15 '21 at 15:57
  • Your solution works as in my expectation. Is there any function you know like require.context with the URL parameter, instead of a directory? We will also upload these images to Google Cloud Storage. We want to probably get images from the cloud via its URL instead of local directory if we can do. I know, I ask lots of questions, sorry for that. – Utku Demir Jan 15 '21 at 18:12
  • I think you guys should create a job to pull your assets (image) first via most likely the service api before building the web app. – tmhao2005 Jan 15 '21 at 18:24