Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: onPress: How can I toggle the button text and function call?

I have a button that looks like this...

<View style={styles.addToFavoritesStyle}>
  <Button onPress={this.addToFavorites}>ADD TO FAVORITES</Button>
</View>

addToFavorites() {
  ...run some code
}

After the user presses the button, how can I change the button text to "REMOVE FROM FAVORITES", change the button styles, and call a different function?

like image 811
Steve Avatar asked Jun 15 '26 00:06

Steve


2 Answers

You'll want to take advantage of state. In your component add a constructor:

constructor(props) {
  super(props);
  this.state = {
    inFavorites: false
  }
}

Make your Button look like this:

<Button onPress={this.addToFavorites}>
  {this.state.inFavorites ? "REMOVE FROM " : "ADD TO " + "FAVORITES"}
</Button>

In your addToFavorites() function add a call to set the state of your component:

this.setState({ inFavorites: true});

This is not an all inclusive example, but it will set the state of your component. You'll have to set the state again when they remove the item from favorites.

like image 116
ajthyng Avatar answered Jun 17 '26 18:06

ajthyng


This is quite a basic question, I suggest you read the React documentation before coming here.

To give you a basic overview though, when you click the button(onClick) you would call a function that changes the state, causing a re-render which in that re-render, you would have a condition like so...

{this.state.addedToFavorites ? "Remove from favorites" : "Add to favorites"}
like image 25
Francis Malloch Avatar answered Jun 17 '26 16:06

Francis Malloch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!