Add DOM nodes to react hierarchy

Viewed 27

How can I insert a DOM node using vanilla javascript into a hierarchy of DOM nodes created by react such that React will not remove it when the state changes.

Reason: I am developing a browser extension, and would like to tightly integrate with an existing site. The existing site uses React under the hood, and I would like to insert a node into the DOM.

Issue: Inserting the node works, but as soon as some state in the react app changes, it removes the custom node from the DOM.

How can I insert and element which will not be removed?

1 Answers

I don't think you can (but you might be able to work around it).

React's job is, in large part, to reconcile the state of the DOM with the state of the React element tree the code using React gives it. After the code has "rendered" React elements, React "commits" that structure to the DOM, doing a diff between the structure the React element tree describes and the structure that's there: removing things that shouldn't be there, adding things that are missing, and updating things that should be there but need their state updated. When it does that, it will see the element you added, see that it's not supposed to be there, and remove it.

The first workaround that comes to mind for your use case is to add the element and use a MutationObserver to watch for it being removed, adding it back if (when) it is.

Related