Answer the question
In order to leave comments, you need to log in
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
.....
}
}
<Button onClick={this.toggle('collapse_2')}></Button>
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
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>
toggle = ({ target: { dataset: { name } } }) => {
this.setState(({ collapse }) => ({
collaple: {
...collapse,
[name]: !collapse[name],
},
}));
}
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
}
]
}
this.setState({
{...state.collapse, [name]: !state.collapse.[name]};
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question