React Native multiple switches

Viewed 6522

On React-Native, I'm trying to create a screen with multiple switch components, with the possibility of selecting only one at once. When the component loads, only the first switch in on. if you click on it, it turns to off, but if you turn on another one, all the others turn to off.

I'm not sure I have the right approach here, as I'm confused about how to use the component state to do this.

In JS, I would do something like a function that turns all switch to off, but turn on the clicked one, but I don't understand how to this with state.

thanks in advance

import React from 'react'
import { ScrollView, Text, View, Switch } from 'react-native'

class switchScreen extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      trueSwitchIsOn: true,
      falseSwitchIsOn: false
    }
  }

  switch = (value) => {
    this.setState({ falseSwitchIsOn: value, trueSwitchIsOn: !value })
  }

  render () {
    return (
      <View>
        <Switch
          onValueChange={this.switch}
          value={this.state.trueSwitchIsOn}
        />
        <Switch
          onValueChange={this.switch}
          value={this.state.falseSwitchIsOn}
        />
        <Switch
          onValueChange={this.switch}
          value={this.state.falseSwitchIsOn}
        />
      </View>
    )
  }
}
3 Answers

You can try something like below, you can keep array of switch states, in the example its an associative key, but you can change according to your need, with multi level switch states. (pardon the code formatting but it give you the idea)

constructor(props) {
super(props);
this.state = {
  switchStates: {
    companyName: true
  }
}
}

toggle(item, index) {
const switchStates = this.state.switchStates;
switchStates[index] = !switchStates[index];
console.log(switchStates);
this.setState({ switchStates });}

render switch

<Switch
    onValueChange={isSwitchOn =>
    this.toggle({ isSwitchOn }, "companyName")
    }
    value={this.state.switchStates.companyName}
/>
Related