Is there any proper way to integrate d3.js graphics into Facebook React application?
d3.js, facebook, javascript, reactjs
Solution
One strategy might be to build a black-box component that you never let React update. The component life cycle method `shouldComponentUpdate()` is intended to allow a component to determine on its own whether or not a rerender is necessary. If you always return `false` from this method, React will never dive into child elements (that is, unless you call `forceUpdate()`), so this will act as a sort of firewall against React's deep update system.
Use the first call to `render()` to produce the container for the chart, then draw the chart itself with D3 within the `componentDidMount()` method. Then it just comes down to updating your chart in response to updates to the React component. Though you might not supposed to do something like that in `shouldComponentUpdate()`, I see no real reason you can't go ahead and call the D3 update from there (see the code for the React component's `_performUpdateIfNecessary()`).
So your component would look something like this:
React.createClass({
render: function() {
return <svg></svg>;
},
componentDidMount: function() {
d3.select(this.getDOMNode())
.call(chart(this.props));
},
shouldComponentUpdate: function(props) {
d3.select(this.getDOMNode())
.call(chart(props));
return false;
}
});
Note that you need to call your chart both in the `componentDidMount()` method (for the first render) as well as in `shouldComponentUpdate()` (for subsequent updates). Also note that you need a way to pass the component properties or state to the chart, and that they are context-specific: in the first render, they have already been set on `this.props` and `this.state`, but in later updates the new properties are not yet set on the component, so you need to use the function parameters instead.
See the jsfiddle here.
Problem
Yes, I know there is react-art, but it seems to be broken. The problem is that d3.js is all about mutating the browser DOM, and using it directly, say inside componentDidMount method, will not work properly, because all changes to browser DOM will not be reflected in React's virtual DOM. Any ideas?