Integrating D3 into React







Thibaud Colas - @thibaud_colas

Slides: talks.thib.me/integrating-d3-into-react

This approach is inspired by a blog post from Nicolas Hery. It has also been taken for a spin by the folks at sift science.

Advantages and tradeoffs

  • Clearly separates concerns between D3 (rendering the chart) and React (managing the data & lifecycle)
  • Copy-pasteability of online examples
  • React relies on D3 to output the markup
  • State has to be synchronized between D3 chart and React component
Use this approach if you value the ability to use the chart outside of React and idiomatic D3 code over the performance gains you'll have by using React's virtual DOM for SVG.

export default class ProgressChart extends Chart {

    create() {
        const svg = super.createRoot();
    }

    update(state) {
        const scales = this._scales(state.domain);
        this._drawBar(scales, state.data);
    }
                    

Hooking into React's lifecycle



componentDidMount() {
    this.createChart();
    window.addEventListener('resize', this.createChart);
},

shouldComponentUpdate() {
    if (this.state.chart) {
        this.state.chart.update(this.getChartState());
    }

    return false;
},

componentWillUnmount() {
    this.state.chart.destroy();
    window.removeEventListener('resize', this.createChart);
},
                    

Other approaches


Code + Demo