REACT I want to create an ARRAY with the names of the files of the images in the PUBLIC FOLDER but can`t reach them because they aren't in the SCR folder. Surely is something basic but i'm missing it.
2 Answers
To access the public folder, you have to use process.env.PUBLIC_URL
or %PUBLIC_URL%
:
<img src="%PUBLIC_URL%/images/some_image.png" />
Or, alternatively using Javascript as you want an array:
const images = ['image_1.png', 'image_2.png']
return images.map(image => <img src=`${process.env.PUBLIC_URL}/images/${image}`
As far as I know, there is no way to iterate through all the files in the public folder as webpack has no access to it. You would have to manually enumerate them.
If you instead use the src
folder, it is possible to use import to dynamically using Regez. It looks like this (taken from here):
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|jpe?g|svg)$/));
By the way, unless you have a strong reason not to use the src
folder (for example, images are used outside of Javascript or outside of the React project), it is recommended to add all files inside the src
folder as webpack can do additional optimizations, such as inlining (ie: using Data URI) images.

- 2,484
- 9
- 20
-
Thank you, i read that in the docs but i thought maybe there was a way to solve that. :) – Gabriel Mar 16 '21 at 12:02
I'm not sure I understood your question, you want to dynamically create an array in the code inside your ReactJS app?
For instance, if '/public/image' contains 'img1.png', 'img2.png', you'd get
myArray = ['img1.png', 'img2.png']

- 430
- 3
- 12
-
That's right but as @yuan-hao-chiang said is not possible because webpack don`t allow it, thank you anyway ;) – Gabriel Mar 16 '21 at 11:59