Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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 4 years ago · Juan Pablo Isaza Report

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 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!