How to add passive event listeners in React?

13,061

Solution 1

You can always add event listeners manually in componentDidMount using a reference to your element. And remove them in componentWillUnmount.

class Example extends Component {
  componentDidMount() {
    this.input.addEventListener('keypress', this.onKeyPress, { passive: false });
  }

  componentWillUnmount() {
    this.input.removeEventListener('keypress', this.onKeyPress);
  }

  onKeyPress(e) {
    console.log('key pressed');
  }

  render() {
    return (
     <SomeInputElement ref={ref => this.input = ref} />
    );
  }
}

Solution 2

Just wrap your input with passive listener

    import {PassiveListener} from 'react-event-injector';
    <PassiveListener onKeyPress={this.someListener.bind(this)}>
        <SomeInputElement/>
    </PassiveListener>
Share:
13,061
UtkarshPramodGupta
Author by

UtkarshPramodGupta

Utkarsh is a Full-Stack Developer from India. His mother tongue is JavaScript. He believes: "Nothing is more beautiful than a beautifully written &lt;code/&gt;"

Updated on July 19, 2022

Comments

  • UtkarshPramodGupta
    UtkarshPramodGupta almost 2 years

    To set event listener say, onKeyPress listener on some react input element, we do something like this:

    <SomeInputElement onKeyPress={this.someListener.bind(this)}>
    

    Now, what should I do to make my someListener passive?

  • UtkarshPramodGupta
    UtkarshPramodGupta over 5 years
    I can't really find a module by the name react-event-injector. :/
  • Anton  Korzunov
    Anton Korzunov over 5 years
    Google is fast, but not so fast - github.com/theKashey/react-event-injector
  • Mikhail
    Mikhail over 2 years
    Some strange bug with <canvas> element as the child. Canvas doesn't get rendered at all.