Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Stop decreasing number with built in condition React/JS

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I would use Math.max for this purpose

<Button type="button" size="small" onClick={() => 
            handleUpdateCartQty(item.id,  Math.max(0, item.quantity - 1)}>-</Button>
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!