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

Viewed 343

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?

1 Answers
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.

Related