react-chartjs-2 icon indicating copy to clipboard operation
react-chartjs-2 copied to clipboard

Dynamic plugins array

Open rfdlp opened this issue 5 years ago • 2 comments

Expected behaviour: Render plugins dynamically

Actual behaviour: Plugins render at the first render and do not update

Description I'm having an issue with plugins that use beforeDraw and are rendered conditionally.

My plugins simply draws a text on the upper-left and (conditionally) on the upper-right corner.

When the chart is first rendered, I display only one of the plugins (upper-left). However, the user can change settings on the chart that would enable a second plugin.

Below is the code where I render the chart, receiving the plugins array from my wrapper. When a plugin changes, the dataset also changes and that is rendered correctly, but the new plugins array is not rendered.

Here's my wrapper:

import React from "react";
import { Chart } from "react-chartjs-2";

export default class LineChart extends React.Component {
  chartRef = React.createRef();

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const myChartRef = this.chartRef.current.getContext("2d");
    this.myChart = new Chart(myChartRef, {
      type: "line",
      options: this.props.options,
      plugins: this.props.plugins,
      data: {
        labels: this.props.labels,
        datasets: this.props.datasets
      }
    });
  }

  componentDidUpdate() {
    this.myChart.data.labels = this.props.labels;
    this.myChart.data.datasets = this.props.datasets;
    this.myChart.plugins = this.props.plugins;
    this.myChart.options = options;
    this.myChart.update();
  }

  render() {
    return <canvas ref={this.chartRef} />;
  }
}

And this is how I call it:

<LineChart
  plugins={plugins}
  datasets={datasets}
  labels={labels}
/>

plugins will have 1 or 2 plugins, depending on settings before that. I have seen the plugins on the componentDidUpdate function, so I know they are there

Any help is appreciated!

rfdlp avatar Mar 31 '20 15:03 rfdlp

@rafaeldalpra You can use props redraw. https://github.com/jerairrest/react-chartjs-2/blob/master/src/index.js#L61

nicholasess avatar Apr 18 '20 12:04 nicholasess

Hello, I encountered the same problem. Why not simply add something like

this.chartInstance.config.plugins = this.props.plugins;

in updateChart? The seems to do the trick and seems better than fully recreate the chart.

sthenault avatar Oct 19 '20 13:10 sthenault