Home > database >  override given variable in object | Javascript React
override given variable in object | Javascript React

Time:02-20

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.

CodePudding user response:

I think a Map would be a good choice here.

const [letters, setLetters] = useState(new Map());

function handleClick (input) {
    setLetters(letters.set(input, true));
}

handleClick("A");

If you wish that input MUST be A, B, or C, then you can use an if statement:

const [letters, setLetters] = useState(new Map([
    ["A", false], // default values for map
    ["B", false],
    ["C", false],
]));

function handleClick (input) {
    if (!letters.has(input)) return; // if map doesnt have it, stop

    setLetters(letters.set(input, true));

    // can also use letters.set(input, false) to "turn it off"
}

handleClick("A");

CodePudding user response:

Is this what you are looking for?

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