Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
IT Nachrichten21. September(21.09.2026 um 00:05 Uhr)
YouTube Security VideosŠkoda Peaq im Fahrest: DAS hätten wir nicht erwartet! | CHIP(21.09.2026 um 00:00 Uhr)
Sichere ProgrammierungBackups and other lies(20.09.2026 um 23:42 Uhr)
IT Nachrichten21. September(21.09.2026 um 00:05 Uhr)
YouTube Security VideosŠkoda Peaq im Fahrest: DAS hätten wir nicht erwartet! | CHIP(21.09.2026 um 00:00 Uhr)
Sichere ProgrammierungBackups and other lies(20.09.2026 um 23:42 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Deterministic React Avatar Fallbacks

Reagiere als Erste:r — dein Feedback zählt!

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 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];
};

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);

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;

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.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Deterministic React Avatar Fallbacks

Thematisch verwandte Begriffe: Deterministic, React, Avatar, Fallbacks · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-93957 | A vulnerability has been found in olivier-ls PHP-FTS up to 1.1.3. This a…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick