Best practice to use image in react

Viewed 3179

Just curious how do you use picture in react? I use webpack so I assume it would be like this

import Picture from '../assets/images/mypic.jpeg'

render(){
   <div>
      <Picture />
   </div>
}

but isn't that tedious to import every single images u want to use?

2 Answers

Stole function from here

Have not tested it myself, but it sounds similar to what you're looking for.

const importAll = (r) => r.keys().map(r);

const images = importAll(require.context('../assets/images/', false, /\.(png|jpe?g|svg)$/));


render() {
  return (
    <div>
      {images.map((pic, i) =>
        <img src={pic} alt={`picture-${i}`} />
      }
    </div>
  )
}
Related