How can you remove a Jquery Document Click Listeners Effecting React Element?

For a legacy app we are rewriting parts of web app with React piece by piece. Because of this can't remove junks of document listeners completely. There are lots of different components all over the page that have listeners on them. This is effecting react components performance.

For example; Material UI Toggle Menu, https://codesandbox.io/s/o9970jm69 Toggling menu is fast and responsive to your clicks in example. But for our web app because of these document event listeners, toggle behavior is not the same as the demo.

Is it possible to remove these document click listeners for React elements?

Or is there a way to get rid of from these listener for React components?

Answers:

Answer

Solution #1 for jQuery events

You can use unbind to remove events. If you need know the event name or type, you can see with Chrome Dev Tools

Solution #2 Javascript events

Another method is capture the event and stop the propagation. You can use removeEventListener or set null the property event.

Answer

instead of trying to remove listeners, I suggest you don't attach them in the first place.

... can't remove junks of document listeners completely

since that is not an option, your second best bet is to modify the listeners so that they exit early if event.target is part of react app (you can verify that by doing document.getElementById('#your-react-dom-root').contains(event.listener))

Answer

There are lots of document on click event listeners

You must mean "There are lots of different components all over the page that have listeners on them."

In that case, there are a couple ideas here that may be helpful: Intercept all document link clicks

Answer

It has to be a temporary solution (remove it after your rewrite has ended), because it is quite dirty, but you can just run the jQuery off function on your React Element at mount.

To make it easier to use (and to remove), you can also create a HOC to do it in one place, something like that :

function withJqueryOffEvent(WrappedComponent, event) {
    return class extends React.Component {
        componentDidMount() {
            $(this.el).off(event);
        }

        render() {
            return <WrappedComponent ref={el => this.el = el} {...this.props} />;
        }
    };
}

// use it like any other HOC
withJqueryOffEvent(AnyComponent, 'click');

Here, we just create a basic HOC which accept an event name, attach a ref to the wrapped component in the render, and use this ref in a jquery selector after the mount to do the off.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.