Home > Enterprise >  How can I make my "Click to remove quantity" button not work when quantity reaches 0
How can I make my "Click to remove quantity" button not work when quantity reaches 0

Time:06-18

In the following scenario I was trying to make a simple /- counter like in shopping apps. When I try to add, it works fine. When I remove it should stop working when it comes to 0. How can I do it?

import React from "react";

class Clicks extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }
  clickAdd() {
    this.setState({
      count: this.state.count   1,
    });
  }
  clickRemove() {
    this.setState({
      count: this.state.count - 1,
    });
  }
  render() {
      return(
        <>
          {this.state.count}<br />
          <button onClick={() => this.clickAdd()}>Click to Add Quantity</button>
          <button onClick={() => this.clickRemove()}>Click to Remove Quantity</button>
        </>
      )
    }
  }

export default Clicks;

CodePudding user response:

Use Math.max to ensure a floor of 0?

clickRemove() {
  this.setState({
    count: Math.max(this.state.count - 1, 0),
  });
}

Or with a condition

clickRemove() {
  if (this.state.count > 0) {
    this.setState({
      count: this.state.count - 1,
    });
  }
}

CodePudding user response:

Seems like you just need to add a value check on the clickRemove() Function.

clickRemove() {
    if (this.state.count > 0) {
        this.setState({
            count: this.state.count - 1,
        });
    }
}

Or you could set up a minValue and a maxValue attribute in your react component to make it more versatile.

CodePudding user response:

Add conditional attribute disabled to make the button disabled when it reaches 0


 <button
    disabled = {this.state.count <= 0}
  >

CodePudding user response:

Note: accept CertainPerformance's answer

this is just an addition to his/her answer. Since setState is an async operation you should use a callback each time you are changing the state using the old state.

It most likely will work but when it doesn't, you'll pull your hair out trying to find out what is causing the bug. More of a tip than an answer :)

Here you can read more about this: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Use Math.max to ensure a floor of 0?

clickRemove() {
  this.setState((prevState) => {
      count: Math.max(prevState.count - 1, 0)
    }{
  });
}

Or with a condition

clickRemove() {
  if (this.state.count > 0) {
    this.setState((prevState) => {
      count: prevState.count - 1
    });
  }
}
  • Related