简体   繁体   中英

How to clear/destroy Chart.js canvas when the chart is represented as a react JSX element

I am running into this issue with chart.js where I have a chart on a specific report. When I switch pages to another page that contains chartjs elements and switch back the chart is showing data labels on the charts data points as "x: number, y: number". After reading a bit about this I believe it's because the canvas is not being correctly reset when I switch back to the original chart. the examples of fixes using the clear() or destroy() command that I've found reference the charts canvas. example: Destroy chart.js bar graph to redraw other graph in same <canvas> However in react that's a bit more tricky to get to. My question is, how can I clear the canvas before drawing my graph. Below is the chart component used to draw the graph.

cont Chart: FunctionComponent<Props> = ({data}) => {
  const options = (): ChartOptions => ({
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    tooltips: chartTooltips,
    elements: chartElementsNoLines,
    scales: {
      xAxes: [
        {
          display: true,
          id: 'x-axis-0',
          ticks: {
            suggestedMin: minMax.min,
            suggestedMax: minMax.max,
            maxTicksLimit: 7,
            maxRotation: 0,
            fontFamily: 'Roboto, sans-serif',
            fontSize: 10,
            autoSkip: true,
            callback: value => currency(value, { precision: 0 }).format()
          },
          gridLines: {
            display: false
          }
        }
      ],
      yAxes: [
        {
          type: 'linear',
          display: false,
          ticks: {
            min: 0,
            max: maxY
          },
          id: 'y-axis-0',
          gridLines: {
            display: false
          }
        }
      ]
    }
  })

  return (
     <section>
      <div className={classes.chartContainer}>
        <HorizontalBar
          data-cy="limit-chart"
          data={data}
          options={{ ...options(), ...annotationPlugin() }}
          redraw={true}
          height={80}
        />
      </div>
     </section>
  )
}


I had problems with data and size changes on rerendering, and i found a way to force updating it using ref ( profitChartRef.current.chartInstance.destroy(); ) to destroy chartInstance and then render completely new instance reflecting exactly what has been updated

export const ProfitReportChart = () => {
    const profitChartRef = useRef();

    if (profitChartRef?.current) {
        profitChartRef.current.chartInstance.destroy();
    }

    return <Bar ref={profitChartRef} data={data} options={options} redraw/>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM