Home > OS >  Sorting an array in React after every click issue
Sorting an array in React after every click issue

Time:04-27

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>

CodePudding user response:

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>

CodePudding user response:

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

  • Related