dynamic image source create-react-app

Recently I had to load many images with part of the URL coming from an API and display them on the home page. I loaded them in using require(), you can also use import, this will tell webpack to include those files when it is built and bundled.

loading in the images and displaying them

I will be showing you the code inside the render() method.


render() {
  return (
      {/* looping through all the post that were retrieve from an API */}
      { this.props.posts.map(post => {
        // here we are dynamically creating a path to the image
        // require() returns a string to the path of the image
        const image = require('../../assets/' + post.character + '.png');

        return (
          // we put the image variable we made earlier into the src attribute
          <img key={ post.id } src={ image } alt={ post.character } />
      }) }

We used require() instead of an import statement because they are only allowed at the top of the file.

what is localStorage

localStorage allows you to store and access strings in your browser.

shadowing objects properties in javascript

when creating a property on a object that has the same property name on its prototype it will shadow it.