Peter Babukh Peter Babukh - 1 year ago 133
React JSX Question

Can't pass relative img src route in React + Webpack

I can't dynamically pass relative img src route in React + Webpack with this.props.

This is a very simplified part of the parent component. It iterates some data list and generates ImgComponents passing props. Here is only tiny part of it:

return (
<ImgComponent srcProp={videolist.anotherImage.src} />

The ImgComponent has:

render() {
return (
<img src={`${this.props.srcProp}`} />

In console I get exactly the same route as i pass with this.props.srcProp, but it would not find the folder and the img there. As if webpack does not load the img.
Here is the console:

<img src="framework/assets/images/cover-bigbuckbunny.png" class="_2WcF9ZmcK-9bQX6jKk18Y_" data-reactid=".0.1.1:$comedy.0.0.$">

No matter what route i indicate, the img is never found in the folder.

Here is the webpack config for png:

{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }

BTW. It works fine if i require the file, like:

<img src={require ('framework/assets/images/cover-bigbuckbunny.png')} />

or indicate some remote route, like

Seems like webpack does not load it. What should i do to dynamically load local img files by dynamically passing src with {this.props.src} ? As I can see, the loader loads img fine if i indicate the file with require. But this way i cannot do it dynamically, as require does not take variables.

Answer Source

What I managed to do is to require('../../assets/images/myFirst.img') in the object, containing the routs to the locally stored files:

in playlist.js

export default (
    cartoons: [{
        images: {
        poster: require('../../assets/images/myFirst.png')
      streams: [{
        type: 'mp4',
        url: ''

Then I work with this list as with any object:

import playlist from '../../playlist';

and iterate this object in a usual manner. The image will be there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download