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;
You need just define onError handler than change the state which will trigger component render method and eventually component will re-render with placeholder.
Please, don't use jQuery and React together!
Since there is no perfect answer, I am posting the snippet I use. I am using reusable
Image
component that fallbacks tofallbackSrc
.Since the fallback image could fail again and trigger infinite loop of re-rendering, I added
errored
state.You can use
object
if that's ok with your requirement. Something like below will work perfectly fineCheck this answer for more details https://stackoverflow.com/a/29111371/1334182
Arthur's answer will result in infinite callbacks if fallback image also fails.
To avoid that, first set a state in the constructor for imageLoadError as true :
and then check for this state value in
onError
function to avoid infinite callbacks,the code will look like this :-