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?
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.
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.
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.
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} />
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With