Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 9105

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T07:19:07+00:00 2024-11-28T07:19:07+00:00

Deterministic React Avatar Fallbacks

  • 60k

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.

avatarjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.