1

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 (
      <div>
        <ImgComponent srcProp={videolist.anotherImage.src} />
      </div>
    );

The ImgComponent has:

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

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.$0.0.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 http://route.to.some.img

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.

Peter Babukh
  • 352
  • 5
  • 18

2 Answers2

3

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: 'http://media.w3.org/2010/05/bunny/movie.mp4'
      }]
    });

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.

Peter Babukh
  • 352
  • 5
  • 18
1

Webpack will not traverse your code to find and convert all possible references to files.

Consider following code:

<img src={'/foo/bar/baz.jpg'} />

It is your responsibility (perhaps using a build target) to ensure that baz.jpg is copied into the foo/bar directory under your web app root.

Amey
  • 2,214
  • 2
  • 19
  • 28