I am trying to make a product counter, which can increase and decrease, the current value of the number of products I am showing in an input with "value", the idea is that the user can enter the number of products without using the increase or decrease buttons.
The problem is that when I have a single number between 0-9 and I manually delete that (in the view) it comes out as a NaN value, and automatically the increase and decrease buttons stop working, and the NaN value cannot be deleted either to rewrite a number
import React, { useState } from 'react'
const Products: React.FC = () => {
const [products, setProducts] = useState({
count: 0
})
const handleChange = (e: any) => {
setProducts({count: parseInt(e.target.value)})
}
const decrease = (e: any) => {
if(products.count <= 0){
return
}
setProducts({count: products.count - 1})
}
return (
<div>
<input type='button' onClick={decrease}/>
<input type='text' value={products.count} onChange={handleChange}/>
<input type='button' onClick={() => setProducts({count: products.count + 1})}/>
</div>
)
}
export default Products
Calling parseInt on the empty string gives NaN:
console.log(parseInt(''));
Then, once products gets set to NaN, any further numeric operations on NaN will also result in NaN.
Alternate the numeric input value (with Number) with 0, to turn the empty string into 0:
setProducts({count: Math.round(Number(e.target.value) || 0}))
You can also consider giving the input the attribute type="number" (just for semantic purposes and better UI for the user - it won't affect the JS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With