6

I have an image uri that i want to pass as prop so that i can load it when it when the component is rendered. as i will be changing images i cannot have a static uri. but i keep getting this error

Error: Cannot find module "."

although it does work when i statically load the images. Also i need to use the img element and not Image.

require('./cube.jpg')

here is my code

here is my parent class declaring the component:

<InputSection ref="inputS" ImD={this.getData} imageUri={this.state.imageurl} />

imageurl state is defined as:

imageurl: './cube.jpg',

child component:

return(
<div style={style}>

<br/>

<img  ref="image" src={require(this.props.imageUri)} onLoad={this._onImageChanged.bind(this)} />
<canvas style={{display:'none'}}width={300} height={300} ref="inputCanvas" >

</canvas>
</div>
);
Claudiga
  • 427
  • 1
  • 4
  • 15

2 Answers2

4

Did you try the other way around? I am assuming you will import the images in your parent component. Also the reason you are getting that error is probably because your Parent component and Child component are not in the same directory. The image path is ./cube relative to Parent which means it resides in the same directory as Parent.

Parent Component

<InputSection ref="inputS" ImD={this.getData} imageUri={require(this.state.imageurl)} />

Child Component

<img  ref="image" src={this.props.imageUri} />
Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36
  • The components are in the same directory i tried to directly load image without using require as you suggested but it throws no error and also nothing appears. i also tried to use the absolute path with no luck. – Claudiga Nov 29 '17 at 09:39
  • in order for require to work the component must know the source of the image before the component loads or is initializing right? or is it when the application is build/compile time? – Claudiga Nov 29 '17 at 09:41
0

you can do this

<img src={require(${this.props.YourPropName})} alt="My Image"/>

and take any name as a prop in the tag and then pass it!!

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140