Reputation: 65248
Is it possible to use REactJS without virtual DOM? I find it difficult to use ReactJS with third party tools because of the virtual DOM. It would be much easier to work with if I could turn virtual dom off. Is this possible?
Upvotes: 4
Views: 2381
Reputation: 31983
Part of the raison d'être of React is to avoid making manual DOM manipulations. By using the virtual DOM, React makes as few changes as possible through a process called Reconciliation.
Ideally, you should never manipulate the DOM manually - let React do it. Of course, as you may have found there are situations where that isn't possible (a good example is trying to use d3.js animation within React). As @Mad Scientist mentioned, the best solution if you really need to touch the DOM yourself is to use React's Lifecycle Methods.
Here is an example from code I recently wrote:
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import d3 from 'd3';
module.exports = React.createClass({
mixins: [PureRenderMixin],
componentDidMount () {
this.componentDidUpdate();
},
componentDidUpdate () {
let svg = d3.select(this.svg);
// Now, svg contains the svg DOM node that React rendered for this component
// Do any manual manipulations to that DOM node here
},
_svg (ref) {
this.svg = ref;
},
render () {
let props = this.props;
return (
<svg height={props.height} width={props.width} ref={this._svg}></svg>
);
}
});
What I've done here is used React refs to keep an internal reference to the DOM node rendered by React. Then, in componentDidUpdate
, I use an external library (d3.js in this case) to grab the DOM node using the React ref (instead of looking for it directly in the DOM). Once I have it, I make my changes there. I also use React's PureRenderMixing
to ensure that the component does not needlessly update.
Hope it helps.
Upvotes: 2
Reputation: 18553
Globally disabling the virtual DOM would pretty much defeat the purpose of the React framework, but it can make sense to have individual components that use DOM-manipulating libraries.
I'm assuming here that the problem you're having is that React doesn't know about any DOM changes you do with other tools or libraries, and rerenders your components and overwrites anything you do. To prevent that you can define shouldComponentUpdate
to prevent React from updating your component. Other lifecycle methods like componentWillReceiveProps
can be used to call your third-party library and perform any changes that need to be done when your props change.
A quick search found this tutorial that integrates a third-party library with React. I'm not familiar with this particular library, but the general concepts in there should apply to all cases where you have a DOM-mutating library and need to prevent React from stepping all over it.
Upvotes: 1