Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  5] [ 5]  / answers: 1 / hits: 7597  / 5 Years ago, mon, july 22, 2019, 12:00:00

I have a simple form with two checkboxes for someone to choose one or the other i.e Yes or No not both. Am using the React-native-element toolkit as shown below.



export default class CheckerForm extends React.Component {
state = {
checked: false,
}
handleYesCheck =() => {
this.setState({checked: !this.state.checked})
}

handleNoCheck =() => {
this.setState({checked: !this.state.checked})
}

render(){

const { checked } = this.state
return (
<View>
<CheckBox
center
title='Yes'
checked={checked}
onPress={this.handleYesCheck}
/>
<CheckBox
center
title='No'
checked={checked}
onPress={this.handleNoCheck}
/>
<View>


I want to capture and modify the state of the checkboxes but when I click one of the checkboxes I modify the state of the other i.e both will be checked and unchecked. How can I modify the states of the checkboxes independently such that when I click on Yes, No is unchecked and vice versa? Generally what is the best way to capture the state so that I can use it.


More From » reactjs

 Answers
15

What you can do is have a array of checkboxes, and save in the state the index of the checked one.


state = {
checkedId: -1,
checkboxes: [{
id: "yes",
title: "Yes"
}, {
id: "no",
title: "No"
}]
}

handleCheck = (checkedId) => {
this.setState({
checkedId
})
}

render() {
const {
checkboxes,
checkedId
} = this.state
return ( <
View > {
checkboxes.map(checkbox => ( <
CheckBox center key = {
checkbox.id
}
title = {
checkbox.title
}
checked = {
checkbox.id == checkedId
}
onPress = {
() => this.handleCheck(checkbox.id)
}
/>
)
} <
View >
)
}

This way you can also handle more than two checkboxes and also know which one is checked by the index.


[#6841] Friday, July 19, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
;