Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass image url as prop in React

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>
);
like image 830
Claudiga Avatar asked Nov 29 '17 07:11

Claudiga


1 Answers

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} />
like image 73
Nandu Kalidindi Avatar answered Sep 25 '22 13:09

Nandu Kalidindi