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?
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?
Just wrap your input with passive listener
import {PassiveListener} from 'react-event-injector';
<PassiveListener onKeyPress={this.someListener.bind(this)}>
<SomeInputElement/>
</PassiveListener>
A different way to do this manually is to use refs and useEffect. In some cases useSyncExternalStore is also an option.
const Foo = (props) => {
const ref = useRef();
useEffect(() => {
const { current } = ref;
if (!current) {
return;
}
const abort = new AbortController();
const { signal } = abort;
current.addEventListener('keypress', onKeyPress, { passive: true, signal });
return () => abort.abort();
}, []);
return <input {...props} ref={ref} />;
};
You can always add event listeners manually in
componentDidMount
using a reference to your element. And remove them incomponentWillUnmount
.