Is there any proper way to integrate d3.js graphics into Facebook React application? Is there any proper way to integrate d3.js graphics into Facebook React application? reactjs reactjs

Is there any proper way to integrate d3.js graphics into Facebook React application?


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.


React can also render the SVG elements directly. Here is an example: Ways of Integrating React.js and D3


You can use D3 as a utility- that is, DON'T use D3 to change the DOM. Rather, use D3 for it's scales and axis stuff, but interpolate the outputs of those D3 functions into the html/svg.

Here's an example from my project.

 scale = d3.time.scale()   .range([ 0, 100 ])   .clamp(true)

...which is passed via props to a component...

React.DOM.rect({          x: "#{props.scale(start)}%"          width: "#{Math.abs( props.scale(end) - props.scale(start)) }%"         })

where React binds the data to the elements, rather than D3's selections.