Reputation: 183
I have to change the Checkbox UI from Check to Uncheck and vice versa according to the value of the state : checked.
For that I have used 'react-native-elements'.
My state name is checked
I have also taken two Buttons to change the state value, but the checkbox is not rendering according to value of the state.
I have done as below : Please guide.
Thanks.
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Button,Alert} from 'react-native';
import { CheckBox } from 'react-native-elements'
export default class App extends Component {
constructor (props) {
super(props)
this.state = {
checked: true,
}
}
render() {
return (
<View style={styles.container}>
<CheckBox
title='Click Here'
checked={this.state.checked}
/>
<CheckBox
center
title='Click Here'
checked={this.state.checked}
/>
<Button value="Check"
title="Check"
onPress={()=>{
this.state.checked=true;
Alert.alert("State >>"+this.state.checked);
}}
/>
<Button value="Un-Check"
title="Un-Check"
onPress={()=>{
this.state.checked=false;
Alert.alert("State >"+this.state.checked);
}}
/>
</View>
);
}
}
EDIT
I have done as below :
<Button value="Check"
title="Check"
onPress={()=>{
this.setState((prevState,props)=>({
isChecked=prevState.isChecked
}));
//this.state.isChecked=true;
Alert.alert("State >>"+this.state.isChecked);
}}
/>
But, It gives me syntax error : Unexpected Token (81:23)
Upvotes: 1
Views: 529
Reputation: 2299
replace
this.state.isChecked=true;
with
this.setState({
isChecked : true
})
You can not assign value directly to the state
for that you have to use setState({})
so update you state
as mentioned above
for false use
this.setState({
isChecked : false
})
For EDIT section
this.setState((prevState,props)=>({
isChecked : prevState.isChecked
}));
Use :
inside stae
do not use =
it will give sintext error..
Upvotes: 2
Reputation: 4199
Your onPress in wrong. you need setState
. In addition to @Jay 's Answer,
setState
is asynchronous, meaning if you press the checkbox multiple timesm, things can get messed up.So the best way is to get the prevState
and mutate it instead
For eg: Toggling the state to and fro like in a checkbox
this.setState((prevState, props) => ({
isChecked: prevState.isChecked
}));
Upvotes: 2