Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling React State

consider this as my react state

state = {
a: true,
b: false,
c: false,
d: false,
e: false 
}

Now, I want to toggle the state on button click and if the event is equal to the key (a, b, c, d, e) in my state, I want that to be true and remaining to false. Currently what I am doing is..

someEvent = (event) => {
if (event === "a") this.setState({a: true, b: false, c: false, d: false, e: false})
if (event === "b")this.setState({a: false, b: true, c: false, d: false, e: false})
....
....
....
}

Instead of writing/setting every state to false, I want the given event equal to the key to have true value in my state and everything else to be false,

How can I do it?

like image 533
iRohitBhatia Avatar asked Jun 06 '26 02:06

iRohitBhatia


1 Answers

You can do this by following code:

this.setState({
  a: event === "a",
  b: event === "b",
  c: event === "c",
  d: event === "d",
  e: event === "e"
});
like image 178
Jitesh Manglani Avatar answered Jun 08 '26 16:06

Jitesh Manglani