Search code examples
javascriptreactjsecmascript-6colors

Generate Dark Colors Only in React and JS


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

Solution

    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