ChungHa Brocher_2 : 2021.05.02 How To Effectively Import Multiple Image Files in React

오범준·2021년 5월 1일
0

There might be sometimes when you have to import multiple image files...then code can be as below ..


import A1_ImageOne from 'assets/images/1st/1.png';
import A1_ImageTwo from 'assets/images/1st/2.png';
import A1_ImageThree from 'assets/images/1st/3.png';

import A2_ImageOne from 'assets/images/1st/1.png';
import A2_ImageTwo from 'assets/images/1st/2.png';
import A3_ImageThree from 'assets/images/1st/3.png';

import A3_ImageOne from 'assets/images/1st/1.png';
import A3_ImageTwo from 'assets/images/1st/2.png';
import A3_ImageThree from 'assets/images/1st/3.png';

import A4_ImageOne from 'assets/images/1st/1.png';
import A4_ImageTwo from 'assets/images/1st/2.png';
import A4_ImageThree from 'assets/images/1st/3.png';

import A5_ImageOne from 'assets/images/1st/1.png';
import A5_ImageTwo from 'assets/images/1st/2.png';
import A5_ImageThree from 'assets/images/1st/3.png';

import A6_ImageOne from 'assets/images/1st/1.png';
import A6_ImageTwo from 'assets/images/1st/2.png';
import A6_ImageThree from 'assets/images/1st/3.png';

If...Number of files go exceed the possible number that we can type in hand...we need other method

How ?

1) aggregate all img files in 'images'folder

2) index.js

3) use 'require' to assemble all img files

export const IMAGES_DATA = (function () { 
    let arr = []
    for(let i = 1 ; i <= 6 ; i++ ){
        for(let j = 1 ; j <= 3; j++){
            let tmpImg = require(`assets/images/${i}_${j}.png`).default
            arr.push(tmpImg)
        }
    }
    console.log("arr",arr)
    return arr
})()

console.log(IMAGES_DATA)

4) Export, Import aggregated img files at 'one variable'

import {IMAGES_DATA} from 'assets/images'
profile
Dream of being "물빵개" ( Go abroad for Dance and Programming)

0개의 댓글