Ausnahme gefangen: SSL certificate problem: certificate is not yet valid 📌 Deterministic React Avatar Fallbacks

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Deterministic React Avatar Fallbacks


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

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.

...



📌 Deterministic React Avatar Fallbacks


📈 77.31 Punkte

📌 FUGU Capabilities: Standards & Fallbacks - #AskChrome


📈 29.84 Punkte

📌 ORY Hydra prior v1.0.0-rc.3+oryOS.9 oauth2/fallbacks/error error_hint cross site scripting


📈 29.84 Punkte

📌 Improved font fallbacks


📈 29.84 Punkte

📌 Framework tools for font fallbacks


📈 29.84 Punkte

📌 Fallbacks for HTTP 404 images in HTML and JavaScript


📈 29.84 Punkte

📌 This Week In React #127: Nextra, React-Query, React Documentary, Storybook, Remix, Tamagui, Solito, TC39, Rome...


📈 27.08 Punkte

📌 This Week In React #131: useReducer, Controlled Inputs, Async React, DevTools, React-Query, Storybook, Remix, RN , Expo...


📈 27.08 Punkte

📌 This Week In React #139: React.dev, Remix, Server Components, Error Boundary, Wakuwork, React-Native, Bottom Sheet...


📈 27.08 Punkte

📌 This Week In React #146: Concurrency, Server Components, Next.js, React-Query, Remix, Expo Router, Skia, React-Native...


📈 27.08 Punkte

📌 How To Create A Facebook Avatar | Use Avatar Stickers In Messenger


📈 26.17 Punkte

📌 Avatar 4 und 5 geplant, Avatar 3 könnte aber letzter Film der Reihe sein


📈 26.17 Punkte

📌 Vor dem Kinostart von Avatar 2: Avatar ist wieder im Abo von Disney+ verfügbar


📈 26.17 Punkte

📌 Avatar 2: An diese 11 Dinge aus &quot;Avatar&quot; müsst ihr euch erinnern, bevor ihr die Fortsetzung anseht


📈 26.17 Punkte

📌 Avatar 3: Verrät das &quot;Avatar: The Way of Water&quot;-Bonusmaterial bereits einen großen Spider-Spoiler?


📈 26.17 Punkte

📌 Leider geil - Warum das neue Avatar Spiel überraschend gut ist! | Avatar Frontiers of Pandora


📈 26.17 Punkte

📌 &quot;Avatar&quot; vs. &quot;Avatar - Herr der Elemente&quot;: Hat James Cameron den Titel der Zeichentrickserie geklaut?


📈 26.17 Punkte

📌 &quot;Avatar&quot; vs. &quot;Avatar - Herr der Elemente&quot;: Hat James Cameron den Titel der Zeichentrickserie geklaut?


📈 26.17 Punkte

📌 rr: lightweight recording & deterministic C/C++ debugging


📈 25.36 Punkte

📌 Contrasting Deterministic Linux Execution vs Record-and-Replay of Linux Executions


📈 25.36 Punkte

📌 Citrix Deterministic Network Enhancer up to 3.21.7.17464 memory corruption


📈 25.36 Punkte

📌 Deterministic Networking (DetNet) nimmt Gestalt an


📈 25.36 Punkte

📌 Hermit: Deterministic Linux for Controlled Testing and Software Bug-finding


📈 25.36 Punkte

📌 Probabilistic vs. Deterministic Regression with Tensorflow


📈 25.36 Punkte

📌 Deterministic vs. Probabilistic Deep Learning


📈 25.36 Punkte

📌 Deterministic environment for reproducible builds


📈 25.36 Punkte

📌 Deterministic environment for reproducible builds


📈 25.36 Punkte

📌 When Stochastic Policies Are Better Than Deterministic Ones


📈 25.36 Punkte

📌 Applied Reinforcement Learning VI: Deep Deterministic Policy Gradients (DDPG) for Continuous…


📈 25.36 Punkte

📌 Deep Deterministic Policy Gradients Explained


📈 25.36 Punkte

📌 Meta AI Introduces Priority Sampling: Elevating Machine Learning with Deterministic Code Generation


📈 25.36 Punkte











matomo