Reputation: 3778
I am using the react native switch component and want to change the state of a switch (on/off) programmatically when state changes for another switch. Below is the code I have:
update = (key: string, val: boolean) => {
if(key == 'togglekey') {
this.state.somekey = !val;
}
};
<Switch onValueChange={(v) => this.update('somekey', v)} value={this.state.somekey} />
<Switch onValueChange={(v) => this.update('togglekey', v)} value={this.state.togglekey} />
When I click on the togglekey switch, I am expecting the somekey switch to toggle on or off, but it is not working. Any pointers?
Upvotes: 1
Views: 598
Reputation: 5442
You can't mutate state directly. You must use setState
instead, only then will React acknowledge the state update.
update = (key: string, val: boolean) => {
if(key == 'togglekey') {
this.setState({somekey: !val});
}
};
Upvotes: 1