Reputation: 135
I want to create a char using c3 in React to, later on, be updated each second.
I am trying to follow the example provided by Updating C3 charts on props change with React, but the first step, which is to create the chart, is not happening.
This is my fiddle:
https://jsfiddle.net/69z2wepo/227446/
import c3 from 'c3';
import React from "react";
import ReactDOM from "react-dom";
class Hello extends React.Component {
renderChart() {
this.chart = c3.generate({
bindto:"#chart1",
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
});
}
render() {
this.renderChart()
return <div id="chart1"></div>;
}
}
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
I installed c3 with npm and am importing it in the component.
Thanks for the help.
Upvotes: 2
Views: 3595
Reputation: 76
In your example, it looks like the chart is generated before the selector div is even rendered, so the chart has no where to go. Instead of calling this.renderChart()
in render()
, you can call it componentDidMount
. In that case, render will be called on the initial load, your <div id="chart1"></div>
will be rendered and then renderChart
will run, adding the SVG to the div.
As for updating the data, you can move the column data itself to state, then call setState
with some new data and use componentDidUpdate
to rerender the chart. That might look something like this:
class Chart extends React.Component {
constructor(props) {
super(props);
this.state = {
column1: ['data1', 30, 200, 100, 400, 150, 250],
column2: ['data2', 50, 20, 10, 40, 15, 25],
};
this.changeData = this.changeData.bind(this);
}
renderChart() {
c3.generate({
bindto: "#chart1",
data: {
columns: [this.state.column1, this.state.column2],
},
});
}
componentDidMount() {
this.renderChart();
}
componentDidUpdate() {
this.renderChart();
}
// Changes data to something arbitrary on button click
changeData() {
this.setState({
column1: ['data1', 70, 120, 30, 300, 230, 300],
column2: ['data2', 100, 120, 50, 140, 150, 80],
});
}
render() {
return (
<div>
<div id="chart1"></div>
<button onClick={this.changeData}>Change</button>
</div>
);
}
}
React Lifecycle methods are key here. Here's a handy chart linked from the docs: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
Upvotes: 6