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