D
D
dim5on2019-01-23 12:18:35
JavaScript
dim5on, 2019-01-23 12:18:35

How to set only one true value inside the state of an object, and the rest false?

Good afternoon ! I'm making an accordion component in React.js. I have this state :

this.state = {
    collapse : {
        collapse_1 : true,
        collapse_2 : false,
        collapse_3 : false
        .....
    }
}

Help me write a toggle function that will change the collapse object's state value to true and the rest to false.
Example :
For this button
<Button onClick={this.toggle('collapse_2')}></Button>

Should return a state like this:
this.state = {
    collapse : {
        collapse_1 : false,
        collapse_2 : true,
        collapse_3 : false
        .....
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2019-01-23
@dim5on

Why store data for all objects if only one can be true? - make one property that will contain the name of the active object:

state = {
  active: null,
}

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

<button onClick={this.toggle} data-name="collapse_1"></button>
<button onClick={this.toggle} data-name="collapse_2"></button>
<button onClick={this.toggle} data-name="collapse_3"></button>

Keep all - this is for the case when several objects can be active at the same time:
toggle = ({ target: { dataset: { name } } }) => {
  this.setState(({ collapse }) => ({
    collaple: {
      ...collapse,
      [name]: !collapse[name],
    },
  }));
}

A
Alexander Loginov-Solonitsyn, 2019-01-23
@kasheibess

You can loop through the for in loop on the state.
Basically I would write it like this:

this.state = {
    collapse : [
        {
           id: 1,
           collapse : false
         }
    ]
}

For me it's more versatile. And plus you can, for example, pass the id of a specific object to the click method. Plus on an array it is possible to go through the filter without problems.

A
Andrey Okhotnikov, 2019-01-23
@tsepen

this.setState({
{...state.collapse, [name]: !state.collapse.[name]};
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question