skip to Main Content

I have an <Avatar/> component and the text inside of it is color white,
How do I make sure that its background color is dark so the text can be seen since its dynamically generated?

Codesandbox —–> CLICK HERE

CODE:

  const colors = useMemo(() => {
    const randomColors = persons.map(() => `#${Math.floor(Math.random() * 16777215).toString(16)}`);
    return randomColors;
  }, [persons]);

2

Answers


    1. The random value for each colour component (red, green, blue) is from 0-255. You need to limit to 0 – 127 to ensure that the generated colours are darker.

    2. padStart(2, '0') ensures that each component has two digits in hexadecimal form

    utils.js

    export function randomColors(persons) {
      const darkColors = persons.map(() => {
            // Generate each color component in the lower half (0-127) of the 0-255 range
            const r = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            const g = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            const b = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            return `#${r}${g}${b}`;
      });
      return darkColors;
    }
    

    Inside your react component.

    const colors = useMemo(() => {
        return randomColors(persons)
    }, [persons]);
    

    CODESANDBOX

    Login or Signup to reply.
  1. You’ll need to check the color for its luminance and than adjust it accordingly

      const randomColors = persons.map(() => {
                  let color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
            
                  while (isLight(color)) { //check if color is dark enough
                    color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
                  }
            
                  return color;
                });
            
                return randomColors;
              }, [persons]);
            
              function isLight(color) {
                const hex = color.replace('#', '');
                const r = parseInt(hex.substr(0, 2), 16);
                const g = parseInt(hex.substr(2, 2), 16);
                const b = parseInt(hex.substr(4, 2), 16);
            
            //calculate luminance
                const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
                return luminance > 150;
              }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search