user3348949
user3348949

Reputation: 344

Change a button color by using onPress on React Native

I would like to have button change its color when pressed. I tryed checking out other similar topics but I couldn't find a solution. The code renders and the initial button color is red, but when I press it, nothing happens.

export default class someProgram extends Component {
  render() {

  var buttonColor = "red";

  function changeButtonColor(){
    if(this.buttonColor === "red"){
      this.buttonColor = "green";
    }
    else{
      this.buttonColor = "red";
    }
  }

  return (
    <View style={styles.container}>      
      <Button 
      title="Press me!"
      color={buttonColor}
      onPress={() => {changeButtonColor(buttonColor)}}  
      />
    </View>
  );
 }
}

Upvotes: 2

Views: 15959

Answers (1)

nbkhope
nbkhope

Reputation: 7474

You should keep track of the color in the component state. As a side, make sure to understand what the keyword this really means. Do a console.log(this) and see it for yourself.

Anyway, you can

(1) set the initial state in the constructor;

(2) access value from the state using this.state.someProp

then (3) adjust the state later using this.setState({ someProp: someValue }).

1) Initial State

constructor(props) {
  super(props);

  this.state = {
    buttonColor: 'red'; // default button color goes here
  };
}

2) Accessing the State & 3) Setting New State

onButtonPress = () => {
  this.setState({ buttonColor: 'someNewColor' }); 
}

render() {
  // ...
  return (
    {/* ... */}
    <Button
      color={this.state.buttonColor}
      onPress={onButtonPress}
    />
  )

Note some parts of the code were omitted to focus on the question at hand.

Upvotes: 3

Related Questions