Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState for both increasing and decreasing number?

Tags:

reactjs

just a stupid question from me, how do guys use the useState hook and prevent it from decreasing under negative number, For example, I got the block codes like this:

const [amount, setAmount] = useState(1);
    const handleSetAmount = () => {
            if (amount > 0) {
                return setAmount(amount + 1)
            } else {
                return 0;
            }
    }

   return (
      <AmountContainer>
         <Remove onClick={() => setAmount(amount -1)}/>
         <Amount>{amount}</Amount>
         <Add onClick={handleSetAmount}/>
      </AmountContainer>
      <Button>ADD TO CART</Button>
)

I want the state to stand still 0 if users press on the Remove button (preventing it from showing negative number), press on Add button It will increase 1, but when I wrote like that It didn't work. So anyone here know how to do it please help me, thanks! :3

like image 559
Dennis Nguyen Avatar asked Aug 31 '25 16:08

Dennis Nguyen


2 Answers

Here's a sample of the thing which you want to achieve:

import { useState } from "react";


export default function App() {
  const [state, setState] = useState(1);
  const decrease = () => {
    if (state == 0) return;
    setState(state - 1);
  };
  const increase = () => {
    setState(state + 1);
  };
  return (
    <>
      <button onClick={increase}>+</button>
      <button onClick={decrease}>-</button>
      {state}
    </>
  );
}

Edit nice-sutherland-mgms7

like image 198
Majid M. Avatar answered Sep 02 '25 08:09

Majid M.


Another option is to disable the Remove button when the amount===0

const [amount, setAmount] = useState(1);

return (
  <AmountContainer>
    <Remove disabled={amount===0} onClick={() => setAmount(amount -1)}/>
    <Amount>{amount}</Amount>
    <Add onClick={() => setAmount(amount + 1)}/>
  </AmountContainer>
  <Button>ADD TO CART</Button>
)


like image 39
mhansen Avatar answered Sep 02 '25 08:09

mhansen