skip to Main Content

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


  1. The easiest way to do this is to put slicedLetters in a state variable, like:

    const [slicedLetters, setSlicedLetters] = useState(<initial value>);
    

    Then in the onClick handler getLetterInput you update the slicedLetters variable and remove the element you want, like:

    getLetterInput() {
        ... current logic
    
        setSlicedLetters((_slicedLetters) =>
            _slicedLetters.filter((__slicedLetter) => {
                 // Here you need the logic to exclude the letter
            })
        )
    }
    

    The reason I used _slicedLetters inside setSlicedLetters 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 value slicedLetters within setSlicedLetters.

    After the setSlicedLetters is performed, React will re-render the component by calling the below again (with the updated slicedLetters value),

    slicedLetters.map((l, i) => {})
    

    Now, the letter is removed from the UI!

    Login or Signup to reply.
  2. If a letter is clicked, you can add it to a clickedLetters state from within your getLetterInput, and then filter through slicedLetters like so:

    const [slicedLetters, setSlicedLetters] = React.useState(["a", "b", "c"]);
    const [clickedLetters, setClickedLetters] = React.useState(["a"]);
    
      <div className="letter_wrapper">
        {slicedLetters.filter((l, i) => {
          if (!clickedLetters.includes(l)) {
            return (
              <p key={i} className="letter_container">
                <span onClick={getLetterInput} className="letter">
                  {l}
                </span>
              </p>
            );
          } else {
            return null;
          }
        })}
      </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search