Updating C3 maps on props with React

I am trying to decorate updating a C3 chart written as a React component when data changes. Data is passed to the component from the parent component through its props.

The solutions that I currently "work", but do not seem to be optimal: when new data appears, the entire graph is regenerated. I would like to move to a new state (the lines are flashing, not a solid chart update). The C3 API seems to have a lot of methods, but I can't seem to find how to get to the graph.

var React = require("react");
var c3 = require("c3");

var ChartDailyRev = React.createClass({
    _renderChart: function (data) {
        var chart = c3.generate({
            bindto: '#chart1',
            data: {
              json: data,
              keys: {
                  x: 'date',
                  value: ['requests', 'revenue']
              },
              type: 'spline',
              types: { 'revenue': 'bar' },
              axes: {
                'requests': 'y',
                'revenue': 'y2'
              }
            },
            axis: {
                x: { type: 'timeseries' },
                y2: { show: true }
            }
        });
    },
    componentDidMount: function () {
        this._renderChart(this.props.data);
    },
    render: function () {
        this._renderChart(this.props.data);
        return (
            <div className="row" id="chart1"></div>
        )
    }
});

module.exports = ChartDailyRev;

      

+3


source to share


1 answer


In accordance with the project documentation :

Using the API, you can update the graph after it has been rendered .... API objects can be called through the object returned from generate()

.

So the first thing you need to do is save the link to the diagram when you create it. It's easy enough to attach it directly to the component:

var ChartDailyRev = React.createClass({
    _renderChart: function (data) {
        // save reference to our chart to the instance
        this.chart = c3.generate({
            bindto: '#chart1',
            // ...
        });
    },

    componentDidMount: function () {
        this._renderChart(this.props.data);
    },

    // ...
});

      



Then you want to update the chart when the props are updated; React provides a named lifecycle binding componentWillReceiveProps

that is triggered when props change.

var ChartDailyRev = React.createClass({
    // ...

    componentWillReceiveProps: function (newProps) {
        this.chart.load({
            json: newProps.data
        }); // or whatever API you need
    }
});

      

(Remember to remove this._renderChart

from the function render

.)

+9


source







All Articles