3

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.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
ffas
  • 69
  • 11
  • Have a look at this question: https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack – Dominik Oct 12 '20 at 20:32
  • `require.context(images` should probably be `require.context('./images/wd/'` – cbr Oct 12 '20 at 20:53
  • @Dominik. I have tried many of those methods and didn't work at all. There is no webpack.config.js in the latest versions. – ffas Oct 12 '20 at 21:09
  • @cbr, the path was originally as you described, but even so, the error of "Module not found: Can't resolve './images/wd/' in '/mywebsite/src/components'" still persists. – ffas Oct 12 '20 at 21:10
  • what is "/wd/" in the images path? – Julia Oct 12 '20 at 21:11
  • Is the `images/wd/` directory under `src/components/`? – cbr Oct 12 '20 at 21:11

1 Answers1

1

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;
Julia
  • 674
  • 1
  • 6
  • 18