Created
February 8, 2018 20:18
-
-
Save maccman/239f1aeac1230c99c75d1d270c08a6a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
export default class DefaultImage extends Component { | |
state = { | |
error: null | |
} | |
onError = (error) => { | |
this.setState({error}); | |
} | |
getSrc = () => { | |
const {error} = this.state; | |
const {src, defaultSrc} = this.props; | |
if (error || !src) { | |
return defaultSrc; | |
} else { | |
return src; | |
} | |
} | |
render () { | |
const {defaultSrc, ...props} = this.props; | |
return ( | |
<img {...props} src={this.getSrc()} onError={this.onError} /> | |
) | |
} | |
} | |
DefaultImage.defaultProps = {defaultSrc: '/default.png'}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment