0

So I have a React app with this structure

-MyApp
-public
--images
---Adam.png
---Jane.png
-src
--components

For one of my components I want to show all the images. Is there a way I can get array of the filenames in my public/images folder? I know how to map the array to a list of images but not sure how to get that array of file names in the first place.

Joshua Augustinus
  • 1,468
  • 3
  • 15
  • 28
  • 1
    the client cannot loop through the server directory so you will need to query an endpoint that accesses the directory and returns an array of filenames – Samuel Goldenbaum Aug 18 '20 at 03:55
  • 1
    As Mosè Raguzzini suggested you can, do following https://stackoverflow.com/a/53762705/10996638 – Ubeyt Demir Aug 18 '20 at 03:59

1 Answers1

0

This is natural question when doing this (because alternative is always importing those one by one which seems wrong) but react is in the end builded into some optimized static code. So whole issue is "what would happen if you added another image to that folder and refreshed page?". And answer is that it cannot react to it because that loop you are doing (one generating img tags or something else) is ran during build. What you need is server that "reads" those folders and lets you know what is there (to your already built app) and you can update state and that renders more elements during runtime in response to server.

In Webpack there is this other option (as mentioned by @UbeytDemir) that can understand what will be public folder and iterate those contents during build, but that still means you have to rebuild the app after each new image, because it simply cant do this during run time without server. It only unifies those imports into one line but imho it's important to understand why this is impossible to do in client's app.