maddy
maddy

Reputation: 4111

setState not updating style in react native

First of all I am very new in react native, and trying to learn it myself and playing around it.

I have a variable name mbackgroundColor. I initialize it in constructor with default value.

constructor(props) {
super(props)
this.state = {
    mbackgroundColor: 'green'
};}

I have a button within JSX and when I click on it i show a alert successfully.

<View style={
[{
height: 50,
}, {backgroundColor : this.state.mbackgroundColor}]
}>
<Button onPress={this.onPressLearnMore}
  title="Learn More"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
/>

Now When I click on button I also want to setState of bbackgroundColor to white and update View also. This is what not happening.

onPressLearnMore() {
Alert.alert('on Press!');
this.setState = {
  mbackgroundColor: 'white'
  };}

I have attached code here.

Thanks for help :)!

Upvotes: 1

Views: 865

Answers (3)

Iman Salehi
Iman Salehi

Reputation: 956

Just set state like this:

this.setState({mbackgroundColor: 'white'})

instead of using:

this.setState = {
  mbackgroundColor: 'white'
  }

Upvotes: 1

Junius L
Junius L

Reputation: 16132

this inside the onPressLearnMore doesn't refer to the current class, which will throw an error, to get this working change your code to the following.

onPressLearnMore = () => {

  Alert.alert('on Press!');

  this.setState({
    mbackgroundColor: 'white',
  });

}

to change the value is state, we use this format this.setState({}) instead of this.state = {}

.setState() tutorial

snack example

And you don't even need the constructor

change

constructor(props) {
  super(props)
  this.state = {
    mbackgroundColor: 'green'
  };
}

to

export default class App extends Component<Props> {

  state = {
    mbackgroundColor: 'green',
  };

  onPressLearnMore = () => {

    Alert.alert('on Press!');
    this.setState({
      mbackgroundColor: 'white',
    });

  };
  ....

Upvotes: 1

Paras Korat
Paras Korat

Reputation: 2065

Change Your code

From

onPressLearnMore() {
Alert.alert('on Press!');
this.setState = {
  mbackgroundColor: 'white'
  };}

To

onPressLearnMore() {
this.setState({mbackgroundColor: 'white'},()=>Alert.alert('on Press!')) 
}

Upvotes: 2

Related Questions