Home > Blockchain >  When I click on the button, if the value of the button is 0, then the text will not show in that spa
When I click on the button, if the value of the button is 0, then the text will not show in that spa

Time:09-29

When I click on the button, if the value of the button is 0, then the text will not show in that space. I mean, how can it be done without showing -10?

console.log(variable)

The this is the error I'm getting ..


const Mobile = () => {

   const [charge, setCharge] = useState(20)

   const setMobileCharge = () => setCharge(charge - 10)

   if (setMobileCharge === 0) {
      return 0;
   }

   return (
      <div>
         <h3>Charge : {charge}</h3>
         <button onClick={setMobileCharge}>Battery down</button>
      </div>
   );
};

export default Mobile;

CodePudding user response:

this happens because the react "ticks" your render is not fully synced with the state ... so to prevent that you can set the new state like that

setCharge(oldCharge => oldCharge -10 )

CodePudding user response:

i don't quite understand your question.if you want when 0 not to decrease, you can :

const setMobileCharge = () => {
  if (charge > 0) {
   setCharge(charge - 10)
  }
}

if you want when 0 Mobile component disappear you can:

if (charge === 0) {
  return 0;
}

CodePudding user response:

you can add a condition like below,

const Mobile = () => {

    const [charge, setCharge] = useState(20)
 
    const setMobileCharge = () => {
      if(charge > 0) setCharge(charge - 10)}   //here
 
    if (setMobileCharge === 0) {
       return 0;
    }
 
    return (
       <div>
          <h3>Charge : {charge === 0 ? "" : charge}</h3>   //here
          <button onClick={setMobileCharge}>Battery down</button>
       </div>
    );
 };
  • Related