Michael
Michael

Reputation: 5

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]
        })}
      />

Upvotes: 0

Views: 668

Answers (2)

Ruchi Tiwari
Ruchi Tiwari

Reputation: 261

Index can be maintained in state and then can be assigned to selectedIndex in onPress and it should work for the selection of different buttons

  this.state = {
   test: "First",
   btnIndex: 0
  }

  <ButtonGroup
    selectedIndex={this.state.btnIndex}
    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], 
    btnIndex: selectedIndex 
  });
    }}
  />

Upvotes: 0

Giovanni Esposito
Giovanni Esposito

Reputation: 11166

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 });
   }}
/>

Upvotes: 0

Related Questions