Search code examples
react-nativeif-statementsetstate

How can I set a state only if there is a condition?


I have a percentage into a text view that changes, but it can't be more than 100%. I use a function with a setstate and I want that if the percentage in the text view is more than 100% it changes in 100%. Something like this:

onPressLearnMore= () => {
        this.setState({

rareperc1: (this.state.rareperc2*this.state.boxes),

rareperc:parseFloat(this.state.rareperc1).toFixed(4),

if(rareperc==100){

rareperc:100,

}
...
        });
  }

The actual code is:

onPressLearnMore= () => {

        this.setState({

                rareperc1: (this.state.rareperc2*this.state.boxes)

                rareperc:parseFloat(this.state.rareperc1).toFixed(4),

...
        });
  }

Solution

  • I solved with this:

          onPressLearnMore= () => {
          var rarepervalue = (this.state.rareperc2*this.state.boxes)+ 
     (this.state.boxes*this.state.incremento1);
          if(rarepervalue>100) rarepervalue=100;
    this.setState({
                percentages: percentuale,
                rareperc1: rarepervalue,
                rareperc:parseFloat(this.state.rareperc1).toFixed(4),