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

Steve picture Steve · Mar 6, 2018 · Viewed 8.7k times · Source

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?

Answer

ajthyng picture ajthyng · Mar 6, 2018

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.