0

I'm trying a simple use-case where a value of an input type number should change using a mouse scroll. It is working when I used useState hook to the input. Value is not updating, instead, the page is scrolling. Don't know what is missing.

Please see the example block of code

import React from 'react'

const NumberField = () =>{

   const [inputValue, setInputValue] = useState()
 
   const handleInputChange = (event:React.ChangeEvent<HTMLInputElement>)=>{
       const value = event.target.value
       setInputValue(value)
   }

   return(
       <input type="number" value={inputValue} onChange={handleInputChange}>
   )
}

Can anyone please provide a solution to update the value on scroll and at the same time page should not scroll when the value is updating in the input field. Thanks.

Antonio Erdeljac
  • 2,974
  • 1
  • 17
  • 24
praveen guda
  • 97
  • 2
  • 10
  • You want the input value to change when scrolling the page? – Moshe Sommers Oct 01 '20 at 17:52
  • Not when scrolling the page but, when I click on the input field and then scroll. Just like the normal input type number field https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_number. – praveen guda Oct 01 '20 at 19:39

1 Answers1

0

You can use the onWheel event react docs.

Handle Wheel Scroll function

const handleWheelScroll = (event:React.WheelEvent<HTMLElement>) => {
    if(event.deltaY > 0){
        setInputValue(inputValue - 1);
    }else{
        setInputValue(inputValue + 1);
    }
}

Or in short

const handleWheelScroll = (event:React.WheelEvent<HTMLElement>) => {
    setInputValue(inputValue + (event.deltaY > 0 ? -1 : 1));
}

Than in your render

<input onWheel={handleWheelScroll} type="number" value={inputValue} onChange={handleInputChange} />

Credits to https://stackoverflow.com/a/34147719/7645069 for up and down checking code

Moshe Sommers
  • 1,466
  • 7
  • 11