Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Erdal SATIK Avatar asked Dec 23 '18 21:12

Erdal SATIK


People also ask

How do I remove listener from react?

Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.

Which mode allows you to remove all event listeners from an element?

removeEventListener() The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.

Are event listeners removed when element is removed?

According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.

Does replaceChild remove event listeners?

replaceChild(new_element, old_element); Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.


2 Answers

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.

like image 94
Mosè Raguzzini Avatar answered Sep 28 '22 06:09

Mosè Raguzzini


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))

like image 21
zhirzh Avatar answered Sep 28 '22 05:09

zhirzh