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>
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 <code/>"
Updated on July 19, 2022Comments
-
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 over 5 yearsI can't really find a module by the name react-event-injector. :/
-
Anton Korzunov over 5 yearsGoogle is fast, but not so fast - github.com/theKashey/react-event-injector
-
Mikhail over 2 yearsSome strange bug with
<canvas>
element as the child. Canvas doesn't get rendered at all.