React render component withtout breaking tree when using other libraries

Viewed 40

Some situation

I am currently using the js library code-mirror (v5) (a text editor with some nice features, such as syntax highlighting) and i must add widgets to it using its API.

It is quite straightforward, you just give code-mirror's API the html element you created for the occasion and it will add it to the page document inside the dom it generated for the editor.

So i just mount a new react component on the HTML element i fed to the code-mirror API. It is correctly rendered without errors, but...

The Problem

While the method above works I'm quite sure that's not the way to do it for multiple reasons.

  • The created component lose the parent context (so change to props doesn't update the created component & stores such as redux are inaccessible)
  • It breaks from the app react tree
  • It is not cleaned up with the destruction of any component and will just remain in memory until we use ReactDOM.unmountAtNode()

I tried stuff with portals but it doesn't seems to be what i need in this case (if i got it right portals do render things outside of the react tree)

Example

This an example of a method that would add a react component to the codemirror as a widget

function addWidget(component: ReactElement, position: Position): void {
    const div = document.createElement('div');

    ReactDOM.render(component, div);

    //code mirror api
    editor.addWidget(position, div, false);
}

Conclusion

I am looking for React best practices in these cases where components needs to be mounted on dynamically created HTML element without losing context and still being attached to some part of the app react tree.

Thank for your time.

0 Answers
Related