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:
JavaScript
x
47
47
1
import React from 'react';
2
import {Link} from 'react-router';
3
import ContactStore from '../stores/ContactStore'
4
import ContactActions from '../actions/ContactActions';
5
6
class Contact extends React.Component {
7
constructor(props) {
8
super(props);
9
this.state = ContactStore.getState();
10
this.onChange = this.onChange.bind(this);
11
}
12
13
componentDidMount() {
14
ContactStore.listen(this.onChange);
15
ContactActions.getContact(this.props.params.id);
16
}
17
18
componentWillUnmount() {
19
ContactStore.unlisten(this.onChange);
20
}
21
22
componentDidUpdate(prevProps) {
23
if (prevProps.params.id !== this.props.params.id) {
24
ContactActions.getContact(this.props.params.id);
25
}
26
}
27
28
onChange(state) {
29
this.setState(state);
30
}
31
32
render() {
33
return (
34
<div className='container'>
35
<div className='list-group'>
36
<div className='list-group-item animated fadeIn'>
37
<h4>{this.state.contact.displayname}</h4>
38
<img src={this.state.imageUrl} />
39
</div>
40
</div>
41
</div>
42
);
43
}
44
}
45
46
export default Contact;
47
Advertisement
Answer
Since there is no perfect answer, I am posting the snippet I use. I am using reusable Image
component that falls back to fallbackSrc
.
Since the fallback image could fail again and trigger infinite loop of re-rendering, I added errored
state.
JavaScript
1
44
44
1
import React, { Component } from 'react';
2
import PropTypes from 'prop-types';
3
4
class Image extends Component {
5
constructor(props) {
6
super(props);
7
8
this.state = {
9
src: props.src,
10
errored: false,
11
};
12
}
13
14
onError = () => {
15
if (!this.state.errored) {
16
this.setState({
17
src: this.props.fallbackSrc,
18
errored: true,
19
});
20
}
21
}
22
23
render() {
24
const { src } = this.state;
25
const {
26
src: _1,
27
fallbackSrc: _2,
28
props
29
} = this.props;
30
31
return (
32
<img
33
src={src}
34
onError={this.onError}
35
{props}
36
/>
37
);
38
}
39
}
40
41
Image.propTypes = {
42
src: PropTypes.string,
43
fallbackSrc: PropTypes.string,
44
};