Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import a group of images as an array? (create-react-app project)

Is it possible to import a group of images as an array? (create-react-app project) like written below but as a single-line?

import Hat1 from '../../assets/img/accesories/hats/hat1.png';
import Hat2 from '../../assets/img/accesories/hats/hat2.png';
import Hat3 from '../../assets/img/accesories/hats/hat3.png';
import Hat4 from '../../assets/img/accesories/hats/hat4.png';
import Hat5 from '../../assets/img/accesories/hats/hat5.png';
import Hat6 from '../../assets/img/accesories/hats/hat6.png';

const hatsArr = [
    Hat1,
    Hat2,
    Hat3,
    Hat4,
    Hat5,
    Hat6
];
like image 536
nir segev Avatar asked Feb 01 '18 10:02

nir segev


2 Answers

You can't directly import them as an array but you can use a file dedicated to these imports :

images.js :

import Hat1 from '../../assets/img/accesories/hats/hat1.png';
import Hat2 from '../../assets/img/accesories/hats/hat2.png';
import Hat3 from '../../assets/img/accesories/hats/hat3.png';
import Hat4 from '../../assets/img/accesories/hats/hat4.png';
import Hat5 from '../../assets/img/accesories/hats/hat5.png';
import Hat6 from '../../assets/img/accesories/hats/hat6.png';

export default [
    Hat1,
    Hat2,
    Hat3,
    Hat4,
    Hat5,
    Hat6
];

Then import this array in one line in other files :

import hatsArr from './images';

Edit : I think you can do some tricky stuff in webpack.config.js to achieve this one line import but can't help on that.

like image 178
Dyo Avatar answered Sep 22 '22 16:09

Dyo


You can write a separate file to export those images like below:

var AppData = {


adata: {
    "initialdata":[
      {
      "text":"",
      "image":"images/slider1.png"
      },
      {
      "text":"",
      "image":"images/slider2.png"
      },
      {
      "text":"",
      "image":"images/slider3.png"
      }
    ]
  }
}
export default AppData;

and import it in your component like below:

import AppData from './AppData';

class App extends Component {
  constructor() {
    super();
    this.state = AppData.adata;
  }

  render() {
    return (
      <ul className="slider">
        {this.state.initialdata.map(function(item,index) {
            return (
                <li key={index}>
                 <img className="sliderImage" src={`./${item.image}.png`} role="presentation" alt="image"/>
                </li>       
            )
        },this)}
      </ul>
    );
  }
}

Hope this would help and working demo by exporting,importing like this demo

like image 23
Jayavel Avatar answered Sep 22 '22 16:09

Jayavel