N
N
nivaech2019-12-05 00:55:37
JavaScript
nivaech, 2019-12-05 00:55:37

How to more elegantly change multiple state values ​​per click?

There is a drop-down menu that opens on click. There are four of them. And four boolean state values ​​for each of them.

state = {
 sidebarOpenMenu1: false,
 sidebarOpenMenu2: false,
 sidebarOpenMenu3: false,
 sidebarOpenMenu4: false,
}

If you open them one by one, the previous menu does not close, and they overlap each other. The problem was solved in a rough way - an individual condition that if some menu is active, then all others should be closed.
handleSidebarOpenMenu1 = () => {
    this.setState({
         sidebarOpenMenu1: !this.state.sidebarOpenMenu1,
         sidebarOpenMenu2: false,
         sidebarOpenMenu3: false,
         sidebarOpenMenu4: false,
    })
}

handleSidebarOpenMenu2 = () => {
    this.setState({
         sidebarOpenMenu1: false,
         sidebarOpenMenu2: !this.state.sidebarOpenMenu2,
         sidebarOpenMenu3: false,
         sidebarOpenMenu4: false,
    })
}
...

And so on for the four menu items.
Is there a more elegant way to solve the problem without systematic copying?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-12-05
@nivaech

Instead of the state of all elements, store the name/id/index of the public:

state = {
  opened: null,
}

toggle = ({ target: { dataset: { name } } }) => {
  this.setState(({ opened }) => ({
    opened: opened === name ? null : name,
  }));
}

https://jsfiddle.net/bexgm6uz/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question