2

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>
  );
 }
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Worked perfectly. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.