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
CodePudding user response:
I would use Math.max for this purpose
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, Math.max(0, item.quantity - 1)}>-</Button>
CodePudding user response:
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>
CodePudding user response:
I have to point out that it is not always a good practice to use onclick.
I would suggest you to try use addEventListener instead.
Check more here
document.querySelector('button').addEventListener('click', function() {
if (item.quantity > 1) {
handleUpdateCartQty(item.id, item.quantity)
item.quantity--;
}
})
<button type="button" size="small" >-</Button>
CodePudding user response:
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
