I’m creating a game. The user is given 6 letters and they have to make as many words as possible. When each letter is clicked it shows in the display box. I want the clicked letter to disappear from the available letter row so that players cant use the same letter twice. I used .map() to display the 6 letters. How can I make one of them disappear after being clicked?
<div className="letter_wrapper">
{slicedLetters.map((l, i) => {
return (
<p
key={i}
className="letter_container">
<span
onClick={getLetterInput}
className="letter">
{l}
</span>
</p>
);
})}
2
Answers
The easiest way to do this is to put
slicedLetters
in a state variable, like:Then in the
onClick
handlergetLetterInput
you update theslicedLetters
variable and remove the element you want, like:The reason I used
_slicedLetters
insidesetSlicedLetters
is because this operation is an async function (and React batches several of such operations together if required). Hence, its better to not refer to the valueslicedLetters
withinsetSlicedLetters
.After the
setSlicedLetters
is performed, React will re-render the component by calling the below again (with the updatedslicedLetters
value),Now, the letter is removed from the UI!
If a letter is clicked, you can add it to a
clickedLetters
state from within yourgetLetterInput
, and then filter throughslicedLetters
like so: