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?
React native add active class when push the button
12.7k views Asked by Zolotukhin Dmitriy At
2
There are 2 answers
0
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.
First have your define your style "class".
Then you can use a state property in your react component.
example :