I have an image folder in my create-react-app
project with a bunch of images. I want to display every single image in the components.
JavaScript
x
9
1
├── Components
2
│ ├── Icons
3
│ │ ├── Icon.jsx (I want to display every single icon)
4
│
5
│
6
├── Images
7
│ ├── Icons
8
│ │ ├── (over 100 SVG icons)
9
In my .jsx file, I want to loop over every image/icon and display it.
Icons.jsx
JavaScript
1
12
12
1
import React, { Component } from 'react';
2
import Icons from '../../Images/Icons';
3
4
5
class Icons extends Component {
6
render() {
7
return (
8
//Loop over every icon and display it
9
);
10
}
11
}
12
Advertisement
Answer
I had the same scenario where I have to pick images
or SVG
s from the folder and display it. Below is the process I followed :
Folder structure
JavaScript
1
11
11
1
-public
2
-src
3
|-component
4
|-images
5
|-1.png
6
|-2.png
7
|-3.png
8
.
9
.
10
|-some x number.png
11
In component
where ever you want to consume the image
there, you have to do this:
JavaScript
1
25
25
1
export default App;
2
import React from 'react';
3
import ReactDOM from 'react-dom';
4
var listOfImages =[];
5
6
class App extends React.Component{
7
importAll(r) {
8
return r.keys().map(r);
9
}
10
componentWillMount() {
11
listOfImages = this.importAll(require.context('./images/', false, /.(png|jpe?g|svg)$/));
12
}
13
render(){
14
return(
15
<div>
16
{
17
listOfImages.map(
18
(image, index) => <img key={index} src={image} alt="info"></img>
19
)
20
}
21
</div>
22
)
23
}
24
}
25
It worked for me; Give it a try.