3

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?

mobiman
  • 619
  • 1
  • 11
  • 26

2 Answers2

5

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.

ajthyng
  • 1,245
  • 1
  • 12
  • 18
1

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"}
Francis Malloch
  • 1,074
  • 9
  • 20