Wasswa Samuel
Wasswa Samuel

Reputation: 2179

Handling state with multiple checkboxes in React Native

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.

Upvotes: 3

Views: 7744

Answers (1)

Vencovsky
Vencovsky

Reputation: 31713

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.

Upvotes: 4

Related Questions