React native add active class when push the button

12.7k views Asked by At

I have a 3 buttons on react native project iOS app. How can I set class active to clicked button and delete this class from others? Like addClass/removeClass that I had used on jquery?

2

There are 2 answers

0
L. Carbonne On BEST ANSWER

First have your define your style "class".

const styles = StyleSheet.create({
  btnSelected: {
     ...
  },
  notSelected : {
  }
});

Then you can use a state property in your react component.

example :

state = {
  btnSelected: 1
}

<Button 
    style={(this.state.btnSelected== 1)?styles.btnSelected:styles.notSelected}
    onPress={() => this.setState({ btnSelected: 1 })} ... />
<Button 
    style={(this.state.btnSelected== 2)?styles.btnSelected:styles.notSelected} ... 
    onPress={() => this.setState({ btnSelected: 2 })} .../>
<Button 
    style={(this.state.btnSelected== 3)?styles.btnSelected:styles.notSelected} 
    onPress={() => this.setState({ btnSelected: 3 })} ... />
0
jevakallio On

The key concept in React and React Native is, that you don't imperatively set the state of your UI. Instead, you change some state, and then declaratively render the UI based on that.

You could, for example use the local component state (this.state):

  class Buttons extends React.Component {
    state = {
      activeButton: 'first'
    }

    render() {
      return (
        <View>
          <Button
            onPress={() => this.setState({ activeButton: 'first' })}
            isActive={this.state.activeButton === 'first'}
          />
          <Button
            onPress={() => this.setState({ activeButton: 'second' })}
            isActive={this.state.activeButton === 'second'}
          />
          <Button
            onPress={() => this.setState({ activeButton: 'third' })}
            isActive={this.state.activeButton === 'third'}
          />
        </View>
      )
    }
  }

The onPress event handler sets local component state with setState, which causes the component to immediately re-render. The isActive property is then set on all the buttons based on the expression that compares this.state.activeButton with some value.