'override given variable in object | Javascript React

const [letters, setLetters] = useState({
    A: false,
    B: false,
    C: false
})

function handleClick(input){
    setLetters((prevLetters) => ({
        ...prevLetters,
        [input]: true
    }))
}

handleClick("A")

How do I manage that, depending on the input, the correct letter is set to true? So if the input is A, it should be set to true in the letters object.



Solution 1:[1]

If you want to override the existing properties on the letters object you can do something like this

const lettersObject = {
  A: false,
  B: false,
  C: false,
};

const [letters, setLetters] = useState(lettersObject);

function handleClick(input) {
  setLetters({
    ...lettersObject,
    [input]: true,
  });
}

Solution 2:[2]

Is this what you are looking for?

  function handleClick(input) {
    setLetters((prevLetters) => ({
      letters: {
        ...prevLetters,
        input: true
      }
    }));
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huzaifa
Solution 2 Y H R