Reputation: 175
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
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