[Cue dramatic music]
Your mission, should you choose to accept it, is to build a list of contacts that shows a profile picture and a name. For contacts that don’t have a profile picture, you should display their initials instead. There is also one catch: if any of the profile images fail to load, you should show their initials.
I know what you’re thinking: “<img> tags and onerror handlers.”
I would normally agree but this is Mission Impossible so let’s try something different. Say we have a React component that renders our list like this:
Instead of having an <img> tag in this render method, we can break that out into its own <ObjectImage> component and add some logic to it.
The secret here is in using the <object> tag to load our images instead of an <img> tag. Set the data attribute to the image source ie “./images/myimage.jpg” and then set the type attribute to the appropriate content type.
The contents of the <object> tag will be rendered if the object data cannot be rendered, so, you are free to provide whatever alternate content you need there. In our case, we are extracting the contact’s initials from the name. Then, simply style as needed.
[This post will self-destruct in five seconds. Good luck.]