I have a button that should decrease a number. How can I create a condition that stops decreasing when my number is 1 in React?
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity - 1)}>-</Button>
something like that:
if(item.quantity == 1){
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity)}>-</Button>
}else{
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity - 1)}>-</Button>
}
Note
item.quantity holds the value of the number
simply you can use the ternary operator as the handleUpdateCartQty parameter, e.g:
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity <= 1 ? item.quantity : item.quantity - 1)}>-</Button>
There could be multiple ways of achieving this
Let me share 2 ways with you so that you can select one as per your requirements
If a button decrements the count then there may be another way to increment the count
If thats the case then you can disable the decrement count button as soon as your value is 1
disabled={newValue<=1}
The alternative is to add an if condition inside your function
const handleUpdateCartQty = (id, newVal) => {
if(newVal < 1) {
// showNotification('min allowed quantity is 1');
return;
}
// Do update operation
}
If you are not disabling the button and not displaying any notification that min quantity should be 1 while just handling condition inside your code then, It may give an impression to the user that button is not working