Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Add Images React Webpack

I've been trying to figure out how to dynamically add images via React and Webpack. I have an image folder under src/images and a component under src/components/index. I'm using url-loader with the following config for webpack

    {       test: /\.(png|jpg|)$/,       loader: 'url-loader?limit=200000'     } 

Within the component I know I can add require(image_path) for a specific image at the top of the file before I create the component but I want make the component generic and have it take a property with the path for the image that is passed from the parent component.

What I have tried is:

<img src={require(this.props.img)} /> 

For the actual property I have tried pretty much every path I can think of to the image from the project root, from the react app root, and from the component itself.

Filesystem

|-- src |   ` app.js |   `--images |      ` image.jpg |      ` image.jpg |   `-- components |      `parent_component.js |      `child_component.js 

The parent component is basically just a container to hold multiples of the child so...

<ChildComponent img=data.img1 /> <ChildComponent img=data.img2 /> etc.... 

Is there any way in which to do this using react and webpack with url-loader or am I just going down a wrong path to approach this?

like image 917
pandorz Avatar asked Sep 16 '15 15:09

pandorz


2 Answers

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png'; 

and

<img src={LogoImg}/> 

Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

like image 133
mlorber Avatar answered Sep 29 '22 20:09

mlorber


If you are bundling your code at the server-side, then there is nothing stopping you from requiring assets directly from jsx:

<div>   <h1>Image</h1>   <img src={require('./assets/image.png')} /> </div> 
like image 40
James Akwuh Avatar answered Sep 29 '22 19:09

James Akwuh