How to add passive event listeners in React?

UtkarshPramodGupta picture UtkarshPramodGupta · Aug 19, 2018 · Viewed 14k times · Source

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?

Answer

albert200000 picture albert200000 · Oct 19, 2019

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} />
    );
  }
}