18

How do you go about getting mouse wheel events in reactjs?

I have tried onWheel

  render: function() {
    return <div onWheel = {this.wheel} >
       < /div>;
  },

and I have tried onScroll

  render: function() {
    return <div onScroll = {this.wheel} >
       < /div>;
  },

But neither of these events are picked up. See the fiddle below :

https://jsfiddle.net/812jnppf/2/

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
  • Theoretically the onWheel synthetic event is what you want to use, I have bare bones create-react-app app, and onWheel works fine for me. I just can't make your jsfiddle work for wheel events, but click events are no problem: https://jsfiddle.net/812jnppf/8/ – Finbarr O'B Jul 20 '17 at 15:06

2 Answers2

18

First, your div is 0 height, so you don't scroll on it. You don't have to bind this as it is a class (and not an es6 react component). Just do a call to the function with the event as parameter on onWheel event:

https://jsfiddle.net/812jnppf/9/

render: function() {

   return <div style={{height:300, width:300}} onWheel = {(e) => this.wheel(e)} >      < /div>;
},

Of course, you have to clean code to style your div with a var or in css.

EDIT : I set it onWheel and not on onScroll (witch doesn't exist I guess ? confirm it if you know). I saw a SO post about adding scroll event to your component easilly : https://stackoverflow.com/a/29726000/4099279

Nevosis
  • 1,366
  • 1
  • 16
  • 27
  • 1
    ah of course stupid me. It was on the wrong container. My next question would be how to interpret the y=100 y=-100 events, and how to go about getting zooming effect. – Oliver Watkins Jul 21 '17 at 07:23
  • 1
    AFAIK, `(e) => this.wheel(e)` is the same as `this.wheel`, except for creating a new object every time and therefore forcing re-render. +++ `onScroll` exists and works, I'm using it. – maaartinus Feb 07 '19 at 03:53
1

Bind the callback to this:

render: function() {
    return <div onWheel = {this.wheel.bind(this)} >
       < /div>;
}
niellus
  • 74
  • 2