Question

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?

Was it helpful?

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.

OTHER TIPS

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.

I am using useRef -hook to save reference to D3 visualization so that I can control when only the chart needs to be updated when there is other "stuff" in the page.

In D3 I am using reusable chart pattern outlined for example in here: https://www.toptal.com/d3-js/towards-reusable-d3-js-charts.

import React, {useEffect, useRef, useState} from 'react';

import { select } from "d3";

const TestArea = () => {

    const [data, setData] = useState(['red']);
    const refElement = useRef(null);
    const visFunction = useRef(null);

    const initVis = () => {
        visFunction.current = d3Chart().data(data)
        select(refElement.current).call(visFunction.current)         
    }

    const updateVis = () => {
        visFunction.current.data(data);      
    }

    useEffect(() => {

        if(data && data.length){

            if(visFunction.current === null)
                initVis()
            else
                updateVis()

        }
        
    }, [data])

    return (
        <>
            <div ref={refElement} className="d3container"></div>
            <button onClick={() => setData(['blue'])}>Update</button>
        </>
    );
};


const d3Chart = () => {

    let svg;
    let gElem;
    let circles;

    let data = []
    let width = 200;
    let height = 200;

    let updateData;

    function chart(selection){

        selection.each(function(){

            svg = select(this)
                .append('svg')

            gElem = svg
                .append('g')
                .attr('transform', ` translate(${width/2},${height/2})`)

            circles = gElem
                .selectAll("circle")
                .data(data)
                .enter()
                .append("circle")
                    .style("stroke", "none")
                    .style("fill", d => d)
                    .attr("r", 10)
                    .attr("cx", 0)
                    .attr("cy", 0)

            updateData = function() {

                circles = gElem
                    .selectAll("circle")
                    .data(data)
                        .style("fill", d => d)

            }

        })
    }

    chart.data = function(val){

        if(!arguments.length) return data;

        data = val;

        if(typeof updateData === 'function')
            updateData();
   
        return chart

    }

    return chart

}


export default TestArea;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top