Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React use img 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

like image 863
AhnQiraj Avatar asked Oct 25 '25 01:10

AhnQiraj


2 Answers

Remember, 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!

like image 117
Gustavo Garcia Avatar answered Oct 27 '25 14:10

Gustavo Garcia


You have onError={this.onError()} with instant function call. It should be either onError={this.onError.bind(this)} or onError={() => this.onError()}.

like image 34
Samuli Hakoniemi Avatar answered Oct 27 '25 14:10

Samuli Hakoniemi