Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse wheel events in Reactjs

Tags:

reactjs

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/

like image 959
Oliver Watkins Avatar asked Jul 20 '17 14:07

Oliver Watkins


People also ask

How do you get the mouse scroll event in React?

To listen for mouse wheel events in React, we can set the onWheel prop to the mouse wheel event listener. We set onWheel to a function that logs the event object. Now when we scroll up and down with the mouse wheel, we should see the event object logged.

What is mouse wheel event?

Definition and Usage. The onwheel event occurs when the mouse wheel is rolled up or down over an element. The onwheel event also occurs when the user scrolls or zooms in or out of an element by using a touchpad (like the "mouse" of a laptop).

What is SyntheticEvent in React?

Overview. Your event handlers will be passed instances of SyntheticEvent , a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers.

What are synthetic events in React with example?

The examples of the synthetic events are onClick(), onBlur() and onChange(). These all are not real DOM events but react synthetic events. Benefits of using synthetic events: Cross browsers applications are easy to implement.


1 Answers

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

like image 85
Nevosis Avatar answered Oct 10 '22 20:10

Nevosis