Import multiple files into reaction

I am using the create-response application for my response project. It has a web package configured to import images. I want to import several images (e.g. 10) from the image folder into the component. The easiest way to do this is to add some import statements, such as -

import Img0 from '../images/0.png'; import Img1 from '../images/1.png'; import Img2 from '../images/2.png'; import Img3 from '../images/3.png'; import Img4 from '../images/4.png'; import Img5 from '../images/5.png'; import Img6 from '../images/6.png'; ... 

The above code would not be a good choice if we have several files to import. Is there a way to add import statements in a loop? I tried to add a loop, but I was not able to change the variables Img0, Img1, etc. (Using ES6, `` did not work as it converted the variable to a string)

+12
source share
2 answers

You cannot use a single import statement, but you can do this:

 function importAll(r) { let images = {}; r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); }); return images; } const images = importAll(require.context('./images', false, '/\.png/')); <img src={images['0.png']} /> 

Source

+12
source

I think it might be better to use the index file for the image folder.

Suppose you have this structure:

Initial folder structure, where all images are on subfolders inside assets / images

And you need to import all your images into your HomePage component. You can easily create the index.js file in the image folder by exporting all images with require, for example:

 export const Background = require('./bg/background.jpg'); export const First = require('./photos/first.jpg'); export const Second = require('./photos/second.jpg'); export const LinkedIn = require('./social/linkedin.png'); 

Then you can import all of them into your component with a single import.

 import { Background, First, Second, LinkedIn } from '../../assets/images' 

And this will be your final folder structure: Final folder structure where we have an index.js inside assets / images

Hope this helps! ;)

0
source

Source: https://habr.com/ru/post/1268935/


All Articles