I am trying to use a plugin with a react-chartjs doughnut chart. In order to use the plugin (https://www.npmjs.com/package/@scottalan/chartjs-plugin-doughnutlabel), I have to pass options to the component. But when I try to pass options, I get a type error
Type '{ doughnutlabel: { labels: { text: string; font: { size: string; family: string; style: string; weight: string; }; color: string; }[]; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
Object literal may only specify known properties, and 'doughnutlabel' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
My best guess is that ChartOptions
is the wrong type to assign my options
to because I get the same error event without trying to use the plugin with const options: ChartOptions = {}
. My full code is below, any help is appreciated.
import React, { useEffect, ReactNode, Component } from "react"
import { Chart, ChartOptions, registerables } from 'chart.js'
import { Doughnut } from 'react-chartjs-2';
Chart.register(...registerables);
const MyDoughnut = (props: ComponentProps) => {
const renderChart = (percents: number[]) => {
const data = {
datasets: [{
label: 'Progress',
data: percents,
backgroundColor: [
'rgb(255, 99, 132)',
'transparent',
],
hoverOffset: 4,
cutout: "75%",
radius: "100%"
}]
}
const options: ChartOptions = {
responsive: true,
legend: {
display: false,
position: 'top',
},
title: {
display: true,
fontSize: 20,
text: 'My Title'
},
plugins: {
doughnutlabel: {
labels: [
{
text: "Foo",
font: {
size: '60',
family: 'Arial, Helvetica, sans-serif',
style: 'italic',
weight: 'bold'
},
color: '#bc2c1a'
}
]
}
}
}
return <Doughnut options={options} data={data}></Doughnut>
}
const render = (): ReactNode => {
// const percents = props.args["percents"]
const percents = [76, 24];
return (
<span>
{renderChart(percents)}
</span>
)
}
return <div>{render()}</div>
};
I am using react-chartjs-2 version 4.0.0 and react version 17.0.2.
CodePudding user response:
I looked at the source of the plugin and it seems like even if you solve the typing issue it wont work. The reason for this is that you are using V3 of Chart.js while the plugin was written for V2 and never updated. It is self registering and it does this in the wrong way, it defines its default options in the wrong place (both namespaces dont exist anymore).
So if you really want to use this plugin I suggest you take a look at the source and modify it so it works with V3 or downgrade to chart.js v2 where there is no build in typing or find another plugin.
CodePudding user response:
It turns out the typing error can be solved by using any
instead of ChartOptions
.
const options: any = {
...
}
As LeeLenalee pointed out, there is also an issue using this specific plugin with V3 of Chart.js, but using any
worked with another similar plugin.