Dexter
Dexter

Reputation: 528

unable to get an array of svg files from public folder to component in React js

here i am having some 20 svg file's in the images folder

public 
  |-images
        -| 20 svg files 

how ever i am able to retrieve only 1 image that to if set the images src folder

 import React from 'react';

import svg from "../src/images/image1.svg"
class App extends React.Component{

   render(){
     return(
       <div>
         <img src={svg} alt="info"></img>
       </div>
     )
   }
}

export default App;

so here how can i retrieve an array of images from public folder can use in component

update :

say my folder structure is like

public
      |- images
           |-50 images
   src
    |- component1
    |- component 2
           |- component2.js 


  if i am calling in component2.js


   importAll(r) {
        return r.keys().map(r);
      }
      componentWillMount() {
        images = this.importAll(require.context('/public/same-size/', false, /\.(png|jpe?g|svg)$/));
      }
      render(){
        return(
          <div>
            {images.map((image, index) => <img key={index} src={image} alt="info"></img>)}
          </div>
        )
      }

then i am getting error module not found

Upvotes: 0

Views: 939

Answers (1)

Faisal Rahman Avash
Faisal Rahman Avash

Reputation: 1256

I think you can go about it this way:

import React from 'react';

var images = [];

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

export default App;

Upvotes: 2

Related Questions