Ah, avatars. Everyone on the internet just loves putting their face out there for everyone to see, right? Well, not quite. Often times, especially on engineering teams, you'll see a bunch of colorful squares or circles with peoples' initials in them.
This will be a shorter post, but we're going to explore how we can give each user a consistent background color for their default avatar if they haven't provided a profile picture. As a bonus, we're going to explore adding Gravatar support as well.
Building the Base Avatar Component
Let's start off by building a simple avatar component that first attempts to load in a user's profile picture (if provided), otherwise falls back to showing their initials.
import React, { useEffect, useState } from 'react';
interface Props {
imageSrc?: string;
name: string;
}
enum Status {
Idle = 'idle',
Loading = 'loading',
Error = 'error',
Success = 'success',
}
const Avatar: React.FC<Props> = ({ imageSrc, name }) => {
const [status, setStatus] = useState<Status>(imageSrc ? Status.Loading : Status.Idle);
const initials = name
?.split(' ')
.map((chunk) => chunk.charAt(0).toLocaleUpperCase())
.slice(0, 2)
.join('');
useEffect(() => {
if (imageSrc) {
setStatus(Status.Loading);
// Test if the image can be loaded successfully by creating a non-rendered Image element
// and adding event listeners for a "load" or "error"
const img = new Image();
// If the image is loaded successfully, we'll render it
img.onload = () => {
setStatus(Status.Success);
};
// Otherwise, we'll show the initials
img.onerror = () => {
setStatus(Status.Error);
};
// Now that the event handlers have been added, set the source to initiate the image load
img.src = imageSrc;
}
}, [imageSrc]);
const isLoading = status === Status.Loading;
const hasLoadedImage = status === Status.Success;
return (
<div
style={{
height: 64,
width: 64,
overflow: 'hidden',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '50%',
background: '#000',
color: '#FFF',
fontWeight: 'bold',
}}
>
{imageSrc && (isLoading || hasLoadedImage) && (
<img
alt={name}
src={imageSrc}
style={{
display: isLoading ? 'none' : 'block',
height: '100%',
width: '100%',
objectFit: 'cover'
}}
/>s
)}
{!hasLoadedImage && !isLoading && <span>{initials}</span>}
</div>
);
};
export default Avatar;
What we have built so far is an avatar component that has two ways it can display: as the user's initials, or the provided image.
Initially, we hide the img element while we're testing whether the image can be loaded or not. This is particularly handy in the event that you want to default to a Gravatar.
Implementing Gravatar
import md5 from 'crypto-js/md5';
interface Props {
email: string;
name: string;
}
/**
* The GET Gravatar endpoint requires a user's email to be trimmed, lower-cased, and
* hashed by the MD5 hashing algorithm
* More information on using Gravatar at https://gravatar.com/site/implement/images/
*/
const getGravatarForEmail = (email: string) => {
const emailHash = md5(email.trim().toLowerCase()).toString();
// The `d` search param is very important to our avatar, so an error code is returned when a Gravatar isn't found
return `https://www.gravatar.com/avatar/${emailHash}?d=404`;
}
If the image fails to load, we simply render the user's initials. Keep in mind that we're using a naïve implementation to get a user's initials in the example above. As noted in my earlier article about when selecting your potential background colors, or you can deal with the issue programmatically by using a library like . If you learned something, don't hesitate to share.
SOCIAL SHARE CARD GENERATOR