Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda