typescriptreact-nativebuttongroup

Selecting button in React Native ButtonGroup


I have a small problem. I'm using a ButtonGroup which previously worked with two options but now I am offering 4 options.

It renders correctly on the screen but I can only select the first two options. How can I jump between the selections so that I can select different buttons.

Any help is welcome!

      <ButtonGroup
        selectedIndex={this.state.test === "First" ? 0 : 1}
        buttons={["First", "Second", "Third", "Fourth"]}
        containerStyle={{ height: 50 }}
        selectedButtonStyle={{ backgroundColor: "red" }}
        selectedTextStyle={{ color: "white" }}
        textStyle={{ fontSize: 18, fontWeight: '600' }}
        onPress={(selectedIndex) => 
          this.setState({
          test: buttons[selectedIndex]
        })}
      />

Solution

  • This happens because you setted selectedIndex={this.state.test === "First" ? 0 : 1} so you have just 2 indexes (and 4 buttons).

    You could create a state variable to manage index. Something like:

    this.state = {
        ...
        selectedIndex: 0
     }
    ...
    <ButtonGroup
       selectedIndex={this.state.selectedIndex}
       buttons={["First", "Second", "Third", "Fourth"]}
       containerStyle={{ height: 50 }}
       selectedButtonStyle={{ backgroundColor: "red" }}
       selectedTextStyle={{ color: "white" }}
       textStyle={{ fontSize: 18, fontWeight: '600' }}
       onPress={(selectedIndex) => {
          this.setState({ test: buttons[selectedIndex] });
          this.setState({ selectedIndex: selectedIndex });
       }}
    />