Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add passive event listeners in React?

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?

like image 870
UtkarshPramodGupta Avatar asked Aug 19 '18 06:08

UtkarshPramodGupta


People also ask

How do you create a passive listener for an event?

Add a passive flag to every event listener that Lighthouse identified. document. addEventListener('touchstart', onTouchStart, {passive: true}); If you're supporting older browsers that don't support passive event listeners, you'll need to use feature detection or a polyfill.

Can you add two event listeners?

The addEventListener() methodYou can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Does React use event listeners?

When using React, you generally don't need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered. You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default.


1 Answers

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} />
    );
  }
}
like image 127
albert200000 Avatar answered Sep 17 '22 15:09

albert200000