Best Way To Loop Images In React
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 li
Solution 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"
functionimportAll(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
importReact, { Component } from"react";
classMyloopextendsComponent {
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) => (
<imgsrc={image}key={index}alt="info"></img>
))}
</li></ul></>
);
}
}
exportdefaultMyloop;
Post a Comment for "Best Way To Loop Images In React"