Home > other >  How to increase and decrease count by clicking button in react?
How to increase and decrease count by clicking button in react?

Time:01-05

I want to create a increment and decrement counter but i don't understand the matter please help me

 const [quantity, setQuantity] = useState()
      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity()
        }
      }
      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity()
        }
      }

CodePudding user response:

 const [quantity, setQuantity] = useState(0)
      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity(quantity - 1)
        }
      }
      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity(quantity   1)
        }
      }

CodePudding user response:

A sample code for your understanding about react Hooks "useState". ‎

function App() {
  const [counter, setCounter] = useState(1);
  const incrementCounter = () => setCounter(counter   1);
  let decrementCounter = () => setCounter(counter - 1);
  if(counter<=0) {
    decrementCounter = () => setCounter(1);
  }
  return (
    <div> 
      <ButtonIncrement onClickFunc={incrementCounter}/>
      <Display message={counter}/> 
      <ButtonDecrement onClickFunc={decrementCounter}/>
    </div>
  );
}

CodePudding user response:

useState hook in react returns a stateful value, and a function to update it. In this case the setQuantity function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

It should be used like this: setQuantity(newValue);

Probably the correct way of doing it in your code would be:

 const [quantity, setQuantity] = useState(1)

      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity(quantity   1)
        }
      }

      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity(quantity - 1)
        }
      }

I think there are some concepts that you are missing, please take a look at https://reactjs.org/docs/hooks-reference.html if you want to know more :)

CodePudding user response:

You should define a default state first

const [quantity, setQuantity] = useState(0)

and after that you can either use the quantity or previous state of the setQuatity function.

 const handleIncrement = () => {
      setQuantity(prev=>prev  )
      // or
      setQuantity(quantity  )
    }
  }

 const handleIncrement = () => {
      // add logic to prevent negative count here
      setQuantity(prev=>prev--)
      // or
      setQuantity(quantity--)
    }
  }
  •  Tags:  
  • Related