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.

9
  • 1
    Show us what you have tried yet so far. Commented Nov 29, 2018 at 7:17
  • This is one: ` const images = { src: "./images" + (ID) + "/" + (ID) } {Object.keys(images.map(function(imageProps) { return ( <li key={ imageProps.src }> <img src={ imageProps.src } /> </li> ); })}` Commented Nov 29, 2018 at 7:31
  • edit your post with the code. Commented Nov 29, 2018 at 7:37
  • See edits. Thanks! Commented Nov 29, 2018 at 7:45
  • Do you know how many images are there in each folder? Commented Nov 29, 2018 at 7:49

1 Answer 1

0

I am facing the same issue trying to implement this in React. But I was able to do it using JavaScript on HTML. Seems iterating over a directory to display its content is not possible with React. The only solution so far has been to import and map.

Sign up to request clarification or add additional context in comments.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.