DEV Community

Cover image for Deterministic React Avatar Fallbacks
Joshua Slate
Joshua Slate

Posted on • Originally published at joshuaslate.com

Deterministic React Avatar Fallbacks

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;

Enter fullscreen mode Exit fullscreen mode

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`;
}
Enter fullscreen mode Exit fullscreen mode

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 internationalization and localization, some languages don't separate words with whitespace. If your application supports users around the world, you may wish to use Intl.Segmenter for this purpose.

So what's next? Well, the example above shows a boring black circle for every user that doesn't have a Gravatar. In order to make things interesting, let's improve the component to give each user one of several colors. We can accomplish this by creating a simple hashing function of our own.

Deterministically Personalizing Avatar Colors

We will want to choose a piece of user data that isn't expected to change much, if at all. Perhaps an ID or email address. That will be the value we hash to determine a background color for the avatar fallback.

const getBackgroundForStringValue = (str: string | undefined, colorOptions: string[]) => {
  const strHashedAsNumber = (str || '')
    .split('')
    .reduce((accum, val) => val.charCodeAt(0) + accum, str?.length || 0);

  return colorOptions[strHashedAsNumber % colorOptions.length];
};
Enter fullscreen mode Exit fullscreen mode

This will return a consistent color value for any given string. Let's walk through a few sample calls.

const ACCENT_COLORS = [
  '#3db378',
  '#b33d5e',
  '#3d87b3',
  '#b3843d',
];

/**
 * When hashed to a number value, the following UUID is strHashedAsNumber = 2310.
 * 2310 % ACCENT_COLORS.length === 2
 * ACCENT_COLORS[2] === '#3d87b3'
 */
getBackgroundForStringValue('fc81deb7-b0f1-4143-8560-187f6c227800', ACCENT_COLORS);

/**
 * When hashed to a number value, the following UUID is strHashedAsNumber = 2480.
 * 2480 % ACCENT_COLORS.length === 0
 * ACCENT_COLORS[0] === '#3db378'
 */
getBackgroundForStringValue('0f0115dd-adb2-40a8-ae9a-39071d61cb27', ACCENT_COLORS);

/**
 * When hashed to a number value, the following UUID is strHashedAsNumber = 2501.
 * 2501 % ACCENT_COLORS.length === 1
 * ACCENT_COLORS[1] === '#b33d5e'
 */
getBackgroundForStringValue('3e757a86-9d2c-42b4-bbfc-01f1a37f514e', ACCENT_COLORS);
Enter fullscreen mode Exit fullscreen mode

Using a function like this, you can ensure that users have their "own" color that is persistent for them without having to manually assign them a color that's stored on their profile in the database or something to that effect.

Putting It All Together

import React, { useEffect, useState } from 'react';
import md5 from 'crypto-js/md5';

interface Props {
  email: string;
  name: string;
}

enum Status {
  Idle = 'idle',
  Loading = 'loading',
  Error = 'error',
  Success = 'success',
}

const getGravatarForEmail = (email: string) => {
  const emailHash = md5(email.trim().toLowerCase()).toString();

  return `https://www.gravatar.com/avatar/${emailHash}?d=404`;
}

// You could use theme context color names instead of a hard-coded array, if you're using something
// like styled-components.
const ACCENT_COLORS = [
  '#3db378',
  '#b33d5e',
  '#3d87b3',
  '#b3843d',
];

const getBackgroundForStringValue = (str: string | undefined, colorOptions: string[]) => {
  const strHashedAsNumber = (str || '')
    .split('')
    .reduce((accum, val) => val.charCodeAt(0) + accum, str?.length || 0);

  return colorOptions[strHashedAsNumber % colorOptions.length];
};

const Avatar: React.FC<Props> = ({ email, name }) => {
  const gravatarSrc = /\S+@\S+\.\S+/.test(email)
    ? getGravatarForEmail(email)
    : '';
  const [status, setStatus] = useState<Status>(gravatarSrc ? Status.Loading : Status.Idle);
  const initials = name
    ?.split(' ')
    .map((chunk) => chunk.charAt(0).toLocaleUpperCase())
    .slice(0, 2)
    .join('');

  useEffect(() => {
    if (gravatarSrc) {
      setStatus(Status.Loading);

      const img = new Image();
      img.onload = () => {
        setStatus(Status.Success);
      };

      img.onerror = () => {
        setStatus(Status.Error);
      };

      img.src = gravatarSrc;
    }
  }, [gravatarSrc]);
  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: getBackgroundForStringValue(email, ACCENT_COLORS),
        color: '#CBCACAFF',
        fontWeight: 'bold',
      }}
    >
      {gravatarSrc && (isLoading || hasLoadedImage) && (
        <img
          alt={name}
          src={gravatarSrc}
          style={{
            display: isLoading ? 'none' : 'block',
            height: '100%',
            width: '100%',
            objectFit: 'cover'
          }}
        />
      )}

      {!hasLoadedImage && !isLoading && <span>{initials}</span>}
    </div>
  );
};

export default Avatar;
Enter fullscreen mode Exit fullscreen mode

Try it!

Depending on your theme's colors, you may end up with accessibility issues due to insufficient contrast between your background colors and the text color for the initials. You can either be cognizant of the contrast issue when selecting your potential background colors, or you can deal with the issue programmatically by using a library like color to validate that there's enough contrast between your background and font colors, and altering one or the other until an acceptable level is reached.

As always, if I missed something or made a mistake, please reach out to me on Twitter. If you learned something, don't hesitate to share.

Top comments (0)