'How to use scroll wheel as input on react?
I want to be able to use the scroll wheel for changing values on my site instead of scrolling. More simplified I want value to go up by one when I scroll up one step on the mouse and go down by one when scrolling down. How do I do this?
Solution 1:[1]
Using state and ref you can control that y displacement.
class ScrollAwareDiv extends React.Component { constructor(props) {
super(props)
this.myRef = React.createRef()
this.state = {scrollTop: 0}
}
onScroll = () => {
const scrollY = window.scrollY
const scrollTop = this.myRef.current.scrollTop
console.log(`onScroll, window.scrollY: ${scrollY} myRef.scrollTop: ${scrollTop}`)
this.setState({
scrollTop: scrollTop
})
}
render() {
const {
scrollTop
} = this.state
return (
<div
ref={this.myRef}
onScroll={this.onScroll}
style={{
border: '1px solid black',
width: '600px',
height: '100px',
overflow: 'scroll',
}} >
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
</div>
) } }
ReactDOM.render( <ScrollAwareDiv />, document.getElementById('root') );
Check this pen: CodePen
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | h4b1f |
