Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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");
about 4 years ago · Juan Pablo Isaza Report

0

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,
  });
}
about 4 years ago · Juan Pablo Isaza Report

0

Is this what you are looking for?

  function handleClick(input) {
    setLetters((prevLetters) => ({
      letters: {
        ...prevLetters,
        input: true
      }
    }));
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!