React js -[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event

1.9k views Asked by At

I am working on React js on one code where I am using select element and onChange event.

  handleChange = (event) => {
        this.setState({value: event.target.value});
    }

    render() {
        return (
            <div>         
               <label>
                List
                    <select value={this.state.value} onChange={this.handleChange}>
                        <option value="one">One</option>
                        <option value="two">Two</option>
                    </select>
                </label>
            </div>
        )

But I am getting this warning again and again in chrome. "[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.". Is there any resolution for it.

1

There are 1 answers

0
Ignas Damunskis On

Basically, all scroll and touch events expect to be "passive" if preventDefault() is not called. But it's not that easy..

  1. Not all browsers support passive event listener option.
  2. If it's the 3rd party code that is causing the warning, modifying it's source code is a bad bad practice.
  3. Packages like default-passive-events jsut blindly apply passive attribute ignoring the usage of preventDefault() and that might cause your script break..
  4. Applying passive: false to all the events will remove the warning, but will not improve the performance. Whats the point then?

I was dealing with such issue not a long ago and created a package that overwrites EventTarget.prototype.addEventListener and add passive option to all the events that do not preventDefault and if browsers supports it.

https://www.npmjs.com/package/passive-events-support

This not only removed the warning, but also improved the performance. Make sure to pass only necessary events instead of default. In this case just 'mousewheel':

import { passiveSupport } from 'passive-events-support/src/utils'

passiveSupport(['mousewheel'])

If you want a modular way, you can find an example in the docs. Make sure to import this script before any other script that causes that warning.