How to add passive event listeners in React?

20.3k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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

Just wrap your input with passive listener

    import {PassiveListener} from 'react-event-injector';
    <PassiveListener onKeyPress={this.someListener.bind(this)}>
        <SomeInputElement/>
    </PassiveListener>
0
On

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