• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

91
Vistas
Sorting an array in React after every click issue

I'd like to show a variable size array shuffled with images on it. The problem is the array shuffled all the times when I click on a card. I'd like that the array is going to be shuffled just once before the game not after every click on it.

<div className="card-container">
          {deck
            .slice(0, numberOfCards * 2)
            .map((card, index) => (
              <div className="card" onClick={() => cardClicked(index)}>
                <img
                  src={"/images/cards/" + card.image}
                  alt={card.name}
                  className={
                    activeCards.indexOf(index) !== -1 ? "show" : "hide"
                  }
                />
              </div>
            ))
            .sort((a, b) => Math.random() - 0.5)}
        </div>
about 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

assuming that you deck is a state in the component you can do something like this

const [deck, setDeck] = useState(props.deck)


useEffect(() => {
  setDeck(deck => [...deck].sort((a, b) => Math.random() - 0.5))
}, [])


return <div className="card-container">
          {deck
            .slice(0, numberOfCards * 2)
            .map((card, index) => (
              <div key={index} className="card" onClick={() => cardClicked(index)}>
                <img
                  src={"/images/cards/" + card.image}
                  alt={card.name}
                  className={
                    activeCards.indexOf(index) !== -1 ? "show" : "hide"
                  }
                />
              </div>
            ))
            }
        </div>

about 3 years ago · Juan Pablo Isaza Denunciar

0

It's reshuffeled every time because you don't persist the shuffled state and it reruns the logic on every render.

You might want to store a list of image names, or whatever is appropriate in a state variable and rely on that to dictate the order.

const [data, setData] = useState();

useEffect(() => {
  // your shuffle logic
  // setData()
}, [])

then map over the data object. Don't forget the key prop

about 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda