KyleAMathews / react-gravatar

React component for rendering a gravatar profile image
http://kyleamathews.github.io/react-gravatar/
MIT License
279 stars 33 forks source link

Add onError to img element #134

Open cjke opened 7 years ago

cjke commented 7 years ago

Gravatar accepts a type of "404" - which, if the email is invalid, will return a 404 status code (instead of say retro or wavatar, etc).

Currently though, there is no way to capture that and action via react-gravatar. It would be nice to be able to pass in a onError prop, and let it be mounted to the img element. This way, a parent component, could catch it, and render a more app relevant default image.

Alternatively, a defaultComponent prop could be passed, that when a 404 is returned, the react-gravatar would render it instead.

Happy to PR if this aligns with the projects goals

KyleAMathews commented 7 years ago

How about instead we just support a new default called custom? And when default="custom" and gravatar returns null, the component uses as the image src a prop called defaultSrc. How's that sound?

cjke commented 7 years ago

If the react-gravatar component returns null when default="404" that would suffice my requirements - even without the defaultSrc or custom pieces.

The issue at the moment is that the 404 status code from gravatar is currently lost, because it is never captured. If that makes sense?

I don't like filing issues with "It doesn't work for my particular use-case" ... but .... in my particular use-case, I want to render a custom avatar component if they don't have a gravatar account. So if their username is "cjke" it would display a "C" in a circle, if their username is "Kyle", it would show a "K" in a circle. So the fallback is a complete component, not just an image.

So yes, if react-component returned a null if there is a 404, then I could check the nullish value and render out a different component instead.

KyleAMathews commented 7 years ago

Ah gotcha — yeah that makes sense — a backup default component is way more flexible than a backup src.

Cool, let's just go with your original proposal then. Someone could do what I was proposing with a simple img component and if someone in the future wants to support passing in a backup default src string, I'd accept that too.

cjke commented 7 years ago

Groovy I will get a PR together shortly.

cjke commented 7 years ago

Added PR at #135

I've also updated the demo page to demonstrate a simple example of a fallback component.

image

hongbo-miao commented 7 years ago

The PR is actually very useful.. Reopen?

zhuber commented 6 years ago

I need this specific thing, can we please make this happen?

zhuber commented 6 years ago

I have created a PR that provides this functionality: https://github.com/KyleAMathews/react-gravatar/pull/146