Easy Patch to React 17 Event Delegation Upgrade

Patch breaking changes to event delegation on React 17 upgrade.

If you’re upgrading to React 17, you might have encountered some breaking changes on event handlers attached at thedocument level. You can read more about this specific change to event delegation here and one of their proposed fixes here.

In React 17, React will no longer attach event handlers at the document level under the hood. Instead, it will attach them to the root DOM container into which your React tree is rendered

In summary, mounting many React modules onto an application could lead to potential issues when those modules are attaching event handlers at the document level. These handlers, whether coming from the application itself or React modules, can cause issues to the event bubble chain. There are many document reports of these issues here, here, here, here, here, here, here, here, here and here.

Quick easy solution for React applications is to replace all event handlers attached to document to the rootNode of where you mounted your React applications.

First, you must have a way to get the DOM element the React application is being mounted to. Typically in most React examples it usesroot.

You will also have to update the mounting HTML element in some cases. In most cases, you will update the index.html:

You might be wondering why the tabindex="-1" is doing there. There are many events that require a focus in order for the event to be captured. For instance, the keydown event requires the DOM node to be able to have focus. For this patch, we don’t care for the rootNode to be focused so we set the tabindex to "-1". You may also want to add the css style outline: none to the DOM node to remove any kind of unwanted :focus styles being applied.

This is the quick solution to patch up your React application after upgrading to React 17. For the most part, this will fix potential issues related to attaching event handlers at the document level within your application. You may want to revisit how you’re implementing event handlers overall with the React 17 update to event delegations.