phantom phantom - 1 year ago 92
React JSX Question

React render function preventing creating new canvas element on each time invoked - Charts.js

I am using React, Charts.js and react-chart.js.

I am making an API request which returns data that i am then visualizing. The problem I am having is that when the page initially loads it only displays one of the names, an then it renders again and the complete list of three names is shown. The problem is that a new graph is created each time the render function is invoked.

Does anyone know if there is a way to prevent a new graph being created each time, but instead to overwrite the previous graph that was created?

The canvas is being rendered twice, which I guess is expected the way the code is setup. On the first canvas element it just has one name, but then on the second canvas it contains all three names

Please see my code below:

var App = React.createClass({
getInitialState: function() {
return {
names: [],
isLoaded: false
componentDidMount: function() {
$.get(url, function(data) {
names: data,
isLoaded: true
render: function() {
return ( < div > {
this.state.isLoaded ? < Graph names = {
/> : <div>Still Loading... </div >
} < /div>)

var Graph = React.createClass({

render: function() {
var names = [];
for (var i = this.props.artists.length - 1; i >= 0; i--) {

var chartData = {
labels: names,
datasets: [{
data: goals
}, {
data: predictions

return <LineChart data = {chartData} width = "600" height = "250" / >

Answer Source

I think the problem is not on React, but in ChartJS ... It's getting new information... but instead of updating ... it is inserting new canvas..

Try setting redraw.

From the docs

if data passed into the component changes, points will animate between values using chart.js' .update(). If you want the chart destroyed and redrawn on every change, pass in redraw as a prop. For example <LineChart data={this.state.chartData} redraw />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download