I'm implementing an input number using React. This input number has a + and - button that increases or decreases the value inside an input.
The onClick
methods works fine, however, I wonder, what's the method to keep triggering the increase
or decrease
methods while the button keeps pressed.
Here are my methods to update the state:
const increaseValue = () => {
const val = isNaN(tempValue) || tempValue === '' ? 0 : Number(tempValue)
setTempValue(val + 1)
}
const decreaseValue = () => {
const val = isNaN(tempValue) || tempValue === '' ? 0 : Number(tempValue)
setTempValue(val - 1)
}
and here's the component
<div className="flex flex-row h-8 w-20 rounded-lg relative bg-transparent">
<button
className=" bg-action text-action-100 hover:text-gray-300 hover:bg-action-300 h-full w-20 rounded-l cursor-pointer outline-none active:bg-action-200"
onClick={decreaseValue}
>
<span className="m-auto text-md font-thin">−</span>
</button>
<input
className="outline-none focus:outline-none text-center w-full bg-action font-thin text-xs antialiased flex items-center text-white"
name="custom-input-number"
value={tempValue}
onChange={e => {
setTempValue(e.target.value)
type === 'number' && setIsEditing(true)
}}
></input>
<button
className="bg-action text-action-100 hover:text-gray-300 hover:bg-action-300 h-full w-20 rounded-r cursor-pointer active:bg-action-200"
onClick={increaseValue}
>
<span className="m-auto text-md font-thin">+</span>
</button>
</div>
Now, I want to add the feature to keep increasing/decreasing while the button is still pressed.