Reputation: 177
I am mapping through an array of objects called abilities in React Native, that I retrieve from the backend and trying to select each one of them (abilities) assigned to each item. But selecting one of them, selects them all. How to effectively select a single checkbox in handleConfirm?
class Example extends Component {
constructor(props) {
super(props);
this.state = {
checked: false,
};
this.handleConfirm = this.handleConfirm.bind(this);
handleConfirm () {this.setState({ checked: true })}
render() {
const {
checked
} = this.state;
return (
<Container>
<Content contentContainerStyle={styles.container}>
<ListItem style={styles.listAllItems}>
{abilities.map((ability, index) =>
<Button
key={index}
iconLeft
style={styles.button}
>
<Text>{ability.name + '\n'}</Text>
<Right>
<CheckBox
checked={checked}
onPress={ this.handleConfirm()}/>
</Right>
</Button>
)}
</ListItem>
</Content>
</Container>
Upvotes: 2
Views: 2971
Reputation: 2870
Below things you have missed in your code:
1] As you are mapping through array of object, you need to manage each checkbox state, which is missing in your code(i.e. you have used a single variable for maintaining check-boxes state which is not correct). You need a array for managing checked/unchecked status of each checkbox.
2] Also it has been observed that, you are handling only checked true condition. Actually you need to handle toggle(checked=>unchecked and unchecked=>checked).
I have made some modifications in your code for your issue and above specified changes as well:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
checked: []
};
}
isItemChecked(abilityName) {
return this.state.checked.indexOf(abilityName) > -1
}
manageToggle = (evt, abilityName) => {
if (this.isItemChecked(abilityName)) {
this.setState({
checked: this.state.checked.filter(i => i !== abilityName)
})
} else {
this.setState({
checked: [...this.state.checked, abilityName]
})
}
}
render() {
return (
<Container>
<Content contentContainerStyle={styles.container}>
<ListItem style={styles.listAllItems}>
{abilities.map((ability, index) =>
<Button
key={index}
iconLeft
style={styles.button}
>
<Text>{ability.name + '\n'}</Text>
<Right>
<CheckBox
checked={this.isItemChecked(name)}
onPress={evt => this.manageToggle(evt, ability.name)}/>
</Right>
</Button>
)}
</ListItem>
</Content>
</Container>
Upvotes: 4
Reputation: 571
do this for your onPress in your checkBox
onPress={()=>{ this.handleConfirm()}}
Upvotes: 0