Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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'

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda