4

Here's my situation:

I have a directory of folders that contain image files inside them. For example: images/(ID)/(ID)-1 (or 2, 3, etc.).jpg. Where (ID) is variable (I have hundreds of IDs within the images directory).

I'm new to React and still trying to get my way through how to use loops in it. I've tried several different approaches and none have seemed to worked on this specific case.

How would I go about constructing a loop that will iterate over each folder, dynamically, and render the images inside each folder? I have a carousel that I want to call this loop in.

Thank you for any help.

EDIT: I've tried working with these two solutions:

How to iterate images on React?

With my own context:

const images = [{ src: "./images" + ID, alt: "Your description here 1" }];

// ...

{
  images.map(function(imageProps) {
    return (
      <li key={imageProps.src}>
        <img src={imageProps.src} alt={imageProps.alt} />
      </li>
    );
  });
}

And

Dynamically import images from a directory using webpack

With my own context:

function importAll(r) {
  return r.keys().map(r);
}

const images = importAll(
  require.context("./images" + ID, false, /\.(png|jpe?g|svg)$/)
);

With the latter, I figured out that within require.context, you can't have a dynamic variable within the argument otherwise it just throws you an error. The first example, it told me that .map wasn't a function. The error wasn't much help.

ROOT
  • 11,363
  • 5
  • 30
  • 45
rvor
  • 87
  • 1
  • 8
  • edit your post with the code. – Bhojendra Rauniyar Nov 29 '18 at 07:37
  • See edits. Thanks! – rvor Nov 29 '18 at 07:45
  • Do you know how many images are there in each folder? – kiranvj Nov 29 '18 at 07:49
  • It varies. Most of them hold 4 images, but I've seen some folders hold 19. – rvor Nov 29 '18 at 07:52
  • How the **server** exposes the list? Because client (unless you're rendering server side) cannot browse (generally speaking) the server directories... – Adriano Repetti Nov 29 '18 at 08:34
  • I am using a React app called Searchkit. It connects with my server using their SearchkitManager component. I have a JSON file that has a particular field that is being used as an identification number, and it mirrors the ID numbers given to the photo files. Right now, I am able to display one image from the folder using this field (or multiple if I just reuse the code over and over, but then that leads to having dups in the carousel and the code is ugly as hell.) What I'm trying to get is a piece of logic that will go into the folder and render all of the relevant images, and nothing more. – rvor Dec 03 '18 at 05:37
  • Check https://stackoverflow.com/questions/64324949/best-way-to-loop-images-in-react – Sableur Apr 19 '21 at 06:18