get asset images dynamically in React.js

Viewed 132

My assets

/public
  /flags
    flags_a.png
    flags_ramdom_name.png
    flags_ramdon_name2.png
    ...

I want to import all of them dynamically. Such like this...

const allFlags = getImages('/public/flags'); // ['flags_a.png', 'flag_random_name.png', ...]

return (
  <div>
    {allFlags.map((src)=> <img src={src} />);
  </div>
);

How can I achieve it in React.js

1 Answers

I think glob module can help you this will recursively get you all file names with .png

var glob = require("glob")

glob("/public/flags/*.png", options, function (er, files) {
console.log(files)
// files is an array of filenames.

})

install glob with npm link

Related