reactjsreact-nativecheckboxreact-native-component

Fetching label value of switch in react native


I want to achieve functionality of a checkbox with a switch in react-native, as checkbox isn't supported in ios devices. I am not getting on how can I fetch the label value associated with a particular switch. So, the idea is, I have a bunch of options, say A,B,C and each is associated with a switch, and there is a submit button. On click of submit I want to get the labels of those options which are toggled on.

This is the code for selecting various options and each is associated with a switch,

       <Text>A</Text>
       <Switch
           onValueChange = {this.handleToggle}
           value = {toggleValue}
       />
       <Text>B</Text>
       <Switch
           onValueChange = {this.handleToggle}
           value = {toggleValue}
       />
       <Text>C</Text>
       <Switch
           onValueChange = {this.handleToggle}
           value = {toggleValue}
       />

And handleToggle code is this,

handleToggle = event => {
    this.setState(state => ({
        toggleValue: !state.toggleValue
    }));
}

Thanks a lot.


Solution

  • You are using the same function for different switches, clicking on one of them won't give you access to the label of that particular switch. To do so i would suggest to build it like this. This could be a working solution:

    Starting with an array that looks like:

    this.state = {
       data = [
          {
           label: "firstSwitch",
           checked: false,
          },
          {
           label: "secondSwitch",
           checked: false,
          }
       ]
    }
    

    Then, in your render:

    this.state.data.map((item, index) => <Fragment>
          <Text>{item.label}</Text>
          <Switch 
          onValueChange = {() => this.handleToggle(index)}
          />
       </Fragment>
    )
    

    The handleToggle will update the array in the position passed as argument:

    handleToggle = index => {
       let tempArr= this.state.data
       tempArr[index].checked = !tempArr[index].checked
       this.setState({data:tempArr})
    }
    

    The submit button will then check for the checked switches:

    onSubmit = () => {
       let arrOfCheckedSwitches= []
       this.state.data.forEach (item => item.checked && arrOfCheckedSwitches.push(item.label))
       console.log("array of labels :", arrOfCheckedSwitches)
    }
    

    Let me know if there's something that's unclear