Home > Software engineering >  useState for both increasing and decreasing number?
useState for both increasing and decreasing number?

Time:12-12

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

CodePudding user response:

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

CodePudding user response:

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>
)


  • Related