3

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?

Madeline Ries
  • 599
  • 1
  • 8
  • 18
  • Importing the pictures in your code makes it easy for the webpack to package it to the browser. See the graphic on https://webpack.github.io/. Do you not want to include the pictures in the React because of laziness or is it because you want it dynamically load? Generally, for any other questions on standards and best practices I have, I usually go to https://vasanthk.gitbooks.io/react-bits/. – Chase W. Aug 02 '17 at 14:59
  • Check this answer https://stackoverflow.com/questions/45287748/how-to-load-an-image-onto-the-page-with-react-from-dynamic-data/45287962#45287962 – Shubham Khatri Aug 02 '17 at 16:48

2 Answers2

3

You use img tags just like in HTML:

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


render() {
  <div>
    <img src={myPicture} alt="My Picture" />
  </div>
}
adrice727
  • 1,482
  • 12
  • 17
0

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>
  )
}
ram
  • 680
  • 5
  • 15