Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

javascript - How to display every image inside an image folder in react

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.

├── Components
│   ├── Icons
│   │   ├── Icon.jsx (I want to display every single icon)
│  
│  
├── Images
│   ├── Icons
│   │   ├── ... (over 100 SVG icons)

In my .jsx file, I want to loop over every image/icon and display it.

Icons.jsx

import React, { Component } from 'react';
import Icons from '../../Images/Icons';


class Icons extends Component {
  render() {
    return (
      //Loop over every icon and display it
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same scenario where I have to pick images or SVGs from the folder and display it. Below is the process I followed :

Folder structure

  -public
   -src
     |-component
     |-images
        |-1.png
        |-2.png
        |-3.png
        .
        .
        |-some x number.png

In component where ever you want to consume the image there, you have to do this:

export default App;
import React from 'react';
import ReactDOM from 'react-dom';
var listOfImages =[];

class App extends React.Component{
    importAll(r) {
        return r.keys().map(r);
    }
    componentWillMount() {
        listOfImages = this.importAll(require.context('./images/', false, /.(png|jpe?g|svg)$/));
    }
    render(){
        return(
          <div>
              {
                    listOfImages.map(
                      (image, index) =>    <img key={index} src={image} alt="info"></img>
                    )
              }
          </div>
        )
    }
}

It worked for me; Give it a try.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...