pandorz pandorz - 7 months ago 117
React JSX Question

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.


|-- 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 />

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?


Using url-loader, described here, you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';


<img src={LogoImg}/>