score:2

Accepted answer

in react, you want to change the view every time the props or state change. if you're using a dom manipulation library, such as chart.js, this is where the react lifecycle methods come in handy.

https://facebook.github.io/react/docs/component-specs.html

you can use componentwillupdate or componentdidupdate (depending on what suits) to compare the next state to the previous state.

componentwillupdate(nextprops, nextstate) {
    /* optionally include logic comparing nextprops or nextstate
     * to this.props or this.state
     */
    this.linechart.clear();
}

just make sure that it's props/state changes that drive the changes in the chart.

i don't know much about this apparent chart.js bug. but if you do need to re-render the canvas element each time, i would suggest placing a key attribute on the canvas element.

<canvas key={this.uniquekey()} id="linechart" width="688" height="286"></canvas>

quite what this.uniquekey() produces hard to say. but it needs to be different every time the props or state change. and only resort this if simpler methods like chart#clear() (or possibly chart#destroy()) fail.

score:0

try this -

var linechart = react.createclass({
  render: function() {
    return (
      <div id="lineholder" classname="graphholder">
        <h2 classname="sectionheader">earnings per day</h2>
        <canvas ref="linechart" key={this.state.canvasupdatetoggle} width="688" height="286"></canvas>
      </div>
    );
  },
  ctx: {},
  linechart: {},
  getinitialstate:function(){
    return {canvasupdatetoggle:"0"};
  },
  componentdidmount: function() {
    this.drawchart();
  },
  componentdidupdate: function() {
    this.drawchart();
  },
  componentwillreceiveprops:function(){
    var canvasupdatetoggle = this.state.canvasupdatetoggle == 0? 1: 0;
    this.setstate({"canvasupdatetoggle":canvasupdatetoggle});
  },
  drawchart: function() {
    var linedata = {
      labels: this.props.dates,
      datasets: [{
        label: "earnings",
        fillcolor: "rgba(151,187,205,0.2)",
        strokecolor: "rgba(151,187,205,1)",
        pointcolor: "rgba(151,187,205,1)",
        pointstrokecolor: "#fff",
        pointhighlightfill: "#fff",
        pointhighlightstroke: "rgba(151,187,205,1)",
        data: this.props.earnings,
      }]
    }
    this.ctx = this.refs.linechart.getcontext("2d");
    this.linechart = new chart(this.ctx).line(linedata);
  }
});

Related Query

More Query from same tag