Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Integrate external libraries that have lots of DOM building in js

Tags:

reactjs

Some of the non-react libraries I'm using perform some DOM generation with javascript. Ideally, I'd like this to occur in react's render cycle but react doesn't implement some DOM functions.

ie. one library wants to create a fragment for showing a title (using jQuery) which in turn ends up calling document.createDocumentFragment.

A simple work around is to have the library do it's rendering on component mount or update. But I'm trying to render using the virtual DOM. Is there a better approach to re-creating or porting the library?

like image 442
Dave Protasowski Avatar asked Feb 03 '15 16:02

Dave Protasowski


People also ask

Can I have multiple React DOM render?

Before React 16.2, you could render only a single DOM node inside the render method. Now you can render multiple DOM nodes. In order to do this, wrap it inside a parent div which essentially makes it a single DOM node with multiple elements inside it. Fragments in React do not deviate much from their literal meaning.

Is it possible to integrate third party libraries with React?

Third-party libraries can be integrated with class components, also with functional components using Hooks. According to Dan Abramov, they (React Team in Facebook) have no plans to remove ES6 class syntax support in the future.

Does ReactJs use a virtual DOM or original DOM to increase performance?

React uses virtual DOM to enhance its performance. It uses the observable to detect state and prop changes. React uses an efficient diff algorithm to compare the versions of virtual DOM. It then makes sure that batched updates are sent to the real DOM for repainting or re-rendering of the UI.

Does React allow usage of other libraries within itself?

React can be used in any web application. It can be embedded in other applications and, with a little care, other applications can be embedded in React.


1 Answers

You need a "Portal". Take a look at https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md This explains the solution very well, like so:

Methodology:

  1. DOM libs usually manipulate the DOM
  2. React tries to re-render and finds a different DOM than it had last time and freaks out
  3. We hide the DOM manipulation from React by breaking the rendering tree and then reconnecting around the DOM the lib manipulates.
  4. Consumers of our component can stay in React-land.
like image 131
Martin Schmid Avatar answered Sep 25 '22 09:09

Martin Schmid