I create a Image component
class Image extends React.Component {
render() {
return (
<img src= { this.state.imgUrl } onError ={ this.onError() }/>
);
}
onError(){
console.log('Image onError');
this.setState(
{ imgUrl: '../default.png' }
);
}
}
and use it in my view but if one Image not found. all Image Component In view onError
I create a Image component
class Image extends React.Component {
render() {
return (
<img src= { this.state.imgUrl } onError ={ this.onError() }/>
);
}
onError(){
console.log('Image onError');
this.setState(
{ imgUrl: '../default.png' }
);
}
}
and use it in my view but if one Image not found. all Image Component In view onError
Share Improve this question edited Apr 5, 2016 at 7:09 Brigand 86.2k20 gold badges167 silver badges173 bronze badges asked Apr 5, 2016 at 6:36 AhnQirajAhnQiraj 531 gold badge1 silver badge3 bronze badges3 Answers
Reset to default 17Remember, if you want to change the styles of the element and/or change the img source, just do something like this:
<img
src={'original src url goes here'}
alt="example"
onError={(e) => {
e.target.src = '/example/noimage.png' // some replacement image
e.target.style = 'padding: 8px; margin: 16px' // inline styles in html format
}}
/>
Hope it helps!
You have onError={this.onError()}
with instant function call. It should be either onError={this.onError.bind(this)}
or onError={() => this.onError()}
.
As React versions are updated, we recommend using the following code.
<img
src={'original src url goes here'}
alt="example"
onError={(e) => {
e.currentTarget.src = '/example/noimage.png' // some replacement image
}}
/>