Best way to loop images in react

Viewed 763

I have created a project with create-react-app and I have a folder called images inside the source. I want to loop inside the images folder and display them.

So far my code look like this:

import React, { Component } from 'react'
import images from './images/wd/'

const listOfImages = []

class Myloop extends Component {
  importAll(r) {
    return r.keys().map(r)
  }

  componentWillMount() {
    listOfImages = this.importAll(require.context(images, false, /\.(png)$/))
  }

  render() {
    return (
      <>
        <ul>
          <li>
            {listOfImages.map((images, index) => (
              <img src={images} key={index} alt="info"></img>
            ))}
          </li>
        </ul>
      </>
    )
  }
}

export default Myloop

After saving the file I have the following message on the terminal:

Module not found: Can't resolve './images/wd/' in '/mywebsite/src/components'

I'm not sure what is wrong, but any help will be great.

1 Answers

Here is the correct answer Dynamically import images from a directory using webpack You cannot import the whole directory at the same time with only "import"

    function importAll(r) {
      return r.keys().map(r);
    }
    
    const images = importAll(
      require.context("./images/wd", false, /\.(png|jpe?g|svg)$/)
    );

UPD: So in your case remove import, swap images with url and add listOfImages to the state

import React, { Component } from "react";

class Myloop extends Component {
  constructor(props) {
    super(props);
    this.state = { listOfImages: [] };
  }
  importAll(r) {
    return r.keys().map(r);
  }

  componentWillMount() {
    const list = this.importAll(
      require.context("./images/wd", false, /\.(png)$/)
    );
    this.setState({
      listOfImages: list
    });
  }

  render() {
    return (
      <>
        <ul>
          <li>
            {this.state.listOfImages.map((image, index) => (
              <img src={image} key={index} alt="info"></img>
            ))}
          </li>
        </ul>
      </>
    );
  }
}

export default Myloop;
Related