Pedram
Pedram

Reputation: 7879

Is there a way to programmatically change SegmentedControlIOS selected option in React Native?

I have a SegmentedControlIOS component that toggles between two values (percentage and amount), which determines whether a number entered by the user is a percentage value or an amount. I define it as follows:

<SegmentedControlIOS 
  tintColor={"#425E6A"} 
  values={this.state.optionNames} 
  onValueChange={this.setSelectedOption.bind(this)}
  selectedIndex={0}
/>

When the user taps a different button on the same screen that has pre-defined percentages set, it would then make sense for the SegmentedControl to automatically flip over to percent. However, I don't see any way in the documentation to be able to do that.

There doesn't seem to be a way to tie the selected value/index to a state variable, for example, or programmatically set the selected value/index. The closest I can see is pre-selecting an index with the selectedIndex prop. Is this actually possible in React Native?

Upvotes: 0

Views: 567

Answers (1)

Janic Duplessis
Janic Duplessis

Reputation: 687

You can use the selectedIndex prop with state. You need to make sure to update your state in the onChange event to keep it in sync with what the user selected. Then you can just call setState with the index you want to select programmatically and it will work!

Here's a small example that does what you want:

React.createClass({
  getInitialState() {
    return {
      selectedIndex: 0,
    };
  },
  render() {
    return (
      <View>
        <SegmentedControlIOS
          values={['One', 'Two']}
          selectedIndex={this.state.selectedIndex}
          onChange={(event) => {
            this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex});
          }}
        />
        <TouchableWithoutFeedback onPress={() => {
          this.setState({selectedIndex: 1});
        }}>
          <Text>Toggle</Text>
        </TouchableWithoutFeedback>
      </View>
    );
  }
});

Upvotes: 4

Related Questions