Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda