'How can I generate random color from a List ? It is important to stay the same color after refreshing

I want to assign a color to a tag element with a unique id. The color should be selected from a list, and after reloading or refreshing the component, the tag's color shouldn't change. I generated random color by tag id by the below approach, but I couldn't find a way to select the colors from a specific list.

function hashCode(str) {
  //String#hashCode
  var hash = 0
  for (var i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash)
  }
  console.log(hash)
  return hash
}

function intToRGB(i) {
  var c = (i & 0x00ffffff).toString(16).toUpperCase()

  return '00000'.substring(0, 6 - c.length) + c
}

export const colorGenerator = key =>
  intToRGB(hashCode(key)) ? `#${intToRGB(hashCode(key))}` : '#774FFF'



Solution 1:[1]

after reloading or refreshing the component, the tag's color shouldn't change

You can save the color as key value pair in the browser session storage - session storage only lasts as long as the tab is open so if your functions checks and finds an existing color in session storage you use it instead of a random one. https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

I couldn't find a way to select the colors from a specific list.

Define an array that contains all colours in your list. Use the array length as modulo on your random number. This gives you a random array index. colorList[randomIndex] will give you a random color from your list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1