I have a react component that is the detail view from a list.
I am trying to replace the image with a default image if the image does not exist and there is a 404 error.
I would normally use the onerror method in the img tag but that doesn't seem to be working.
I am not sure how to do this with react.
Here is my component:
import React from 'react';
import {Link} from 'react-router';
import ContactStore from '../stores/ContactStore'
import ContactActions from '../actions/ContactActions';
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = ContactStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
ContactStore.listen(this.onChange);
ContactActions.getContact(this.props.params.id);
}
componentWillUnmount() {
ContactStore.unlisten(this.onChange);
}
componentDidUpdate(prevProps) {
if (prevProps.params.id !== this.props.params.id) {
ContactActions.getContact(this.props.params.id);
}
}
onChange(state) {
this.setState(state);
}
render() {
return (
<div className='container'>
<div className='list-group'>
<div className='list-group-item animated fadeIn'>
<h4>{this.state.contact.displayname}</h4>
<img src={this.state.imageUrl} />
</div>
</div>
</div>
);
}
}
export default Contact;
I wrote like this.
This works best for me
Ran into a similar problem and the best solution i could find was Georgii Oleinikov's answer. (Doesn't require making new
imageLoadError
state as suggested by Nitesh Ranjan in his answer)e.target.onerror = null
is not needed (and doesn't really help) because the if condition is enough to prevent the infinite loop(if backup image fails to load as well).So:
EDIT: The other way around is to set a flag outside the return brackets and check for the flag in the if statement. Code should look something like this:
That's how I did it.
If anyone is using image src with require then onError doesn't work as -
then require throws an error, where I tried multiple ways and came to try and catch block solution as -
and use as
You can use uncontrolled component: