reactjsecmascript-6react-hooksmaterial-ui

Generate Random Same Colors in React


I have successfully generated random colors. The problem is I also wanted to assign same random colors for the background color of the same orderNumber. How do I do this?

Please check my codesandbox CLICK HERE

const newColorFind = () => {
  for (let x = 0; x < 6; x++) {
    let index = Math.floor(Math.random() * 16);
    let value = arrayOfColorFunctions[index];

    randomColorString += value;
  }
  console.log(randomColorString);
};

Solution

  • The code in your sandbox isn't tracking:

    1. Previously generated colors
    2. Order numbers that have been assigned a color.

    You can use a map object to track both, which allows for O(1) constant time lookup of either.

    Example:

    const colorMap = {};
    const selectedColors = {};
    
    const generateColor = () => {
      let randomColorString = "#";
      const arrayOfColorFunctions = "0123456789abcdef";
      for (let x = 0; x < 6; x++) {
        let index = Math.floor(Math.random() * 16);
        let value = arrayOfColorFunctions[index];
    
        randomColorString += value;
      }
      return randomColorString;
    };
    
    const newColorFind = id => {
      // If already generated and assigned, return
      if (colorMap[id]) return colorMap[id];
    
      // Generate new random color
      let newColor;
    
      do {
        newColor = generateColor();
      } while(selectedColors[newColor]);
    
      // Found a new random, unassigned color
      colorMap[id] = newColor;
      selectedColors[newColor] = true;
    
      // Return next new color
      return newColor;
    }
    

    Pass the currently iterated orderNumber to the color utility

    <TableCell
      component="th"
      scope="row"
      sx={{ backgroundColor: newColorFind(row.orderNumber) }}
    >
      {row.orderNumber}
    </TableCell>
    

    Edit generate-random-same-colors-in-react

    enter image description here

    Using PolishedJS readableColor utility to select the readable text color to use. enter image description here