So I am working on a project where I am using react native elements checkbox and I finally got it working where it does not select all of the fetched items at one. It only selec
Right now your state have one parameter, checked
, which stores the checked state of an item. That means every time you select another checkbox, the previous selection will be lost. To allow multiple selects we must manage an array of checkbox state. This could be achieved by different approaches, here is the approach I would suggest
First, you need to modify your constructor
constructor(props) {
super(props);
const { navigation } = props;
const cust = navigation.getParam('food', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.parse(cust);
//Here we will make array of object with additional parameter, checked
//This assume cust1 will be ["Pecan Cookies", "Strawberry Cheesecake"]
const data = cust1.map(item=>({label:item, checked:false});
this.state = {
dataSource: [],
data,
checked: null,
}
}
Now let's update your render function
onChecked = (index) => {
let {data} = this.state;
data[index].checked = !data[index].checked;
this.setState({data})
}
render() {
const { data} = this.state;
return (
<View style={styles.container}>
<BackButtonMGMT navigation={this.props.navigation} />
<FlatList data={data} extraData={this.state} keyExtractor={(item, index)=> index.toString()}
renderItem={({ item, index }) => (
<CheckBox center titleProps={{ color: 'black', fontWeight: 'bold'}} title={item.label} iconRight
checked={item.checked} size={30} onPress={()=>this.onChecked(index)}
containerStyle={styles.checkBox}
/>
)}
/>
</View>
)
}
This should solve the problem or having multiple selection.