Eirik Vattøy
Eirik Vattøy

Reputation: 175

Counter no less than 0 using react hooks

In my removeCountHandler I need to find out if the number is less than zero. If it is then keep it at zero

  const [count, setCount] = useState(0);

  const addCountHandler = () => {
    setCount(count + 1);
  };
  const removeCountHandler = () => {
    setCount(count - 1);
  };

  return count <= 1  ? 
    <div>
        {count} person
      <Increment increment={addCountHandler} />
      <Decrement decrement={removeCountHandler} />
    </div>
  :
   <div>
        {count} persons
      <Increment increment={addCountHandler} />
      <Decrement decrement={removeCountHandler} />
    </div>
};


Upvotes: 0

Views: 2562

Answers (1)

Fabian Hinsenkamp
Fabian Hinsenkamp

Reputation: 302

Check out the demo: Demo

Basically, you just check for the counter being zero in the removeCountHandler:

function Counter(){
const [count, setCount] = useState(0);

  const addCountHandler = () => {
    setCount(count + 1);
  };
  const removeCountHandler = () => {
    if(count === 0){
      return;  
    }
    setCount(count - 1);
  };

  return (
    <div>
        {count} person
      <button onClick={addCountHandler}>+</button>
      <button onClick={removeCountHandler}>-</button>
    </div>
  );
};

Upvotes: 2

Related Questions