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.
React
render() {
return (
<div>
{/* 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 } />
);
}) }
</div>
);
}
We used require()
instead of an import
statement because they are only allowed at the top of the file.