Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className list remains unchanged. Below is a snippet of my code:
function TileBoard() {
const [openTileVisible, setOpenTileVisible] = useState(true);
const [shuffler, setShuffler] = useState(0);
const yellowTileIds = [9, 10, 11, 12, 15, 23, 24, 25, 33, 36, 37, 38, 39];
let initialTiles = [];
for (let i = 0; i <= 48; i++) {
if (i === 48) {
initialTiles.push(<Tile key={i} number={i} id={'openTile'} className={openTileVisible ? 'tile-black tile' : 'tile'}/>);
} else {
if (yellowTileIds.includes(i)) {
initialTiles.push(<Tile key={i} number={i} className={'tile-yellow tile'}/>);
} else {
initialTiles.push(<Tile key={i} number={i} className={'tile-black tile'}/>);
}
}
}
const [tiles, setTiles] = useState(initialTiles);
return (
<div className={'game'}>
<div key={shuffler} className={'board'}>
<div className={'tiles'}>
{tiles}
</div>
</div>
<button onClick={() => {
setOpenTileVisible(false);
shuffleArray();
}}>SHUFFLE</button>
</div>
);
}
Despite changing the useState, the class isn't being removed. Am I making a mistake with the className attribute during object creation?
And here's the shuffle method:
function shuffleArray() {
let array = tiles;
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
console.log(array);
setTiles(array);
// Forcing a Rerender since React doesn't recognize changes in element order in the array as a reason to rerender.
setShuffler(shuffler + 1);
}