From 0465582e24d3da7c490e5eba5c3f8358fe06ab35 Mon Sep 17 00:00:00 2001 From: Zak Huber Date: Thu, 12 Jul 2018 12:04:11 -0700 Subject: [PATCH] onError fallback component This which allows users to specify a fallback component, which is great for folks who do not want to fallback to a different image source. For example, users can have a "default profile" component that gets passed in as the `fallback` prop. # Related feature request: https://github.com/KyleAMathews/react-gravatar/issues/134 --- src/index.js | 142 +++++++++++++++++++++++++++++---------------------- 1 file changed, 82 insertions(+), 60 deletions(-) diff --git a/src/index.js b/src/index.js index 87d56b8..d912b5a 100644 --- a/src/index.js +++ b/src/index.js @@ -15,6 +15,7 @@ class Gravatar extends React.Component { className: PropTypes.string, protocol: PropTypes.string, style: PropTypes.object, + fallback: PropTypes.object, } static defaultProps = { size: 50, @@ -23,87 +24,108 @@ class Gravatar extends React.Component { protocol: '//', } + constructor(props, context) { + super(props, context); + this.state = { + display: 'image', + } + } + + _handleErrors = () => { + if (this.props.fallback) { + this.setState({ display: 'fallback' }) + } + } + render() { - const base = `${this.props.protocol}www.gravatar.com/avatar/` + if (this.state.display === 'fallback') { + // Fall back to another default component if the image results in a 404 + return this.props.fallback + } else { + const base = `${this.props.protocol}www.gravatar.com/avatar/` - const query = querystring.stringify({ - s: this.props.size, - r: this.props.rating, - d: this.props.default, - }) + const query = querystring.stringify({ + s: this.props.size, + r: this.props.rating, + d: this.props.default, + }) - const retinaQuery = querystring.stringify({ - s: this.props.size * 2, - r: this.props.rating, - d: this.props.default, - }) + const retinaQuery = querystring.stringify({ + s: this.props.size * 2, + r: this.props.rating, + d: this.props.default, + }) - // Gravatar service currently trims and lowercases all registered emails - const formattedEmail = ('' + this.props.email).trim().toLowerCase(); + // Gravatar service currently trims and lowercases all registered emails + const formattedEmail = ('' + this.props.email).trim().toLowerCase(); - let hash - if (this.props.md5) { - hash = this.props.md5 - } else if (typeof this.props.email === 'string') { - hash = md5(formattedEmail, {encoding: "binary"}) - } else { - console.warn( - 'Gravatar image can not be fetched. Either the "email" or "md5" prop must be specified.' - ) - return (