Reputation: 11
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()
}
}
Upvotes: 0
Views: 12287
Reputation: 1
import React, { Component } from "react"
class Test extends Component { state = { count: 1, }
onIncrement = () => { this.setState((prevState) => { return { count: prevState.count + 1 } }) }
onDecrement = () => { this.setState((prevState) => { return { count: prevState.count - 1 } }) }
render() { return ( {this.state.count} Increment Decrement ) } }
Upvotes: 0
Reputation: 61
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--)
}
}
Upvotes: 0
Reputation: 37
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 :)
Upvotes: 0
Reputation: 321
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>
);
}
Upvotes: 1
Reputation: 109
const [quantity, setQuantity] = useState(0)
const handleIncrement = () => {
if (quantity < 20) {
setQuantity(quantity - 1)
}
}
const handleDecrement = () => {
if (quantity > 1) {
setQuantity(quantity + 1)
}
}
Upvotes: 0