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

285
Views
how to handle multi boolean states in one onClick event in React;

I have 6 sidebar drop menu.

when I click the title, it will show sub-menu.

I can handle that with each onClick function.

like

const [state, setState] = useState({
  one: false,
  two: false,
  three: false,
  four: false,
  five: false,
  six: false,
});

const oneHandler = (e) => {
  e.preventDefault();
  setState({ ...state, one: !state.one });
}

const twoHandler = (e) => {
  e.preventDefault();
  setState({ ...state, two: !state.two });
}

and in return

<div onClick={oneHandler}>First</div>
{state.one ? (
  <div>Something</div>
  ):(
   ""
 )}
<div onClick={twoHandler}>Second</div>
{state.two ? (
  <div>Something</div>
  ):(
   ""
 )}

...repeat

it works but bad codes I think.

So, I tried to make that using one onClick event.

like

const clickHandler = (value) => {
  setState({...state, value: !state.value});
};

...

<div onClick={()=> oneHandler(one)}>First</div>

but in console, it just show false.

I just wanna make it clear and shortly

Can you guys recommend any other methods?

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

0

const clickHandler = (value) => {
  setState({...state, [value]: !state[value]});
};

...

<div onClick={()=> clickHandler('one')}>First</div>
<div onClick={()=> clickHandler('two')}>First</div>
<div onClick={()=> clickHandler('three')}>First</div>

I guess this will solve your issue.

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!