react-chartjs-2
react-chartjs-2 copied to clipboard
Implement HTML Legeng plugin with react-chartjs-2 v4
Would you like to work on a fix?
- [ ] Check this if you would like to implement a PR, we are more than happy to help you go through the process.
Current and expected behavior
Hi guys,
I would like to implement HTML Legeng plugin with react-chartjs-2 in its version 4.
What I would like to have is legends looking like this
possible using charts library (look this pen ) : https://codepen.io/udarakasun/pen/QYLgeM
I used this example that's already in the documentation on Chartjs.org
https://www.chartjs.org/docs/3.9.1/samples/legend/html.html
and this how I have imported charts and instances:
import {
ArcElement,
Chart as ChartJS,
Legend as ChartjsLegend,
Tooltip,
TooltipItem,
TooltipModel,
} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { Doughnut } from 'react-chartjs-2';
this is how my doughnut component is implemented:
const renderDoughnut = useCallback(() => {
const doughnutSize = 300;
return (
<Doughnut
data={{
labels,
datasets: [
{
hoverOffset: 6,
data,
backgroundColor: colors,
datalabels: {
anchor: 'center',
backgroundColor: null,
borderWidth: 0,
},
},
],
}}
width={doughnutSize}
height={doughnutSize}
options={{
responsive: false,
maintainAspectRatio: true,
plugins: {
htmlLegend: {
// ID of the container to put the legend in
containerID: 'legend-container',
},
datalabels: {
backgroundColor: null,
borderColor: 'white',
borderRadius: 25,
borderWidth: 2,
color: 'white',
display: () => true,
font: {
weight: 'bold',
},
padding: 3,
formatter: Math.round,
},
legend: {
display: false,
},
tooltip: tooltips,
},
}}
plugins={[htmlLegendPlugin]}
/>
);
}, [colors, data, labels, tooltips]);
with a failure in compilation , I got this error
there is no dom element with that plugin id
Thank you for your help
Reproduction
https://codesandbox.io/s/hungry-feather-yj81gq?file=/App.tsx
chart.js version
3.9.1
react-chartjs-2 version
4.3.1
Possible solution
No response
Hi @shiiheb 👋
Thank you for bringing this up! We'll definetly look into this issue.
In the mean time you can create your own div
to be used as legendContainer
to get rid of the error. I've modified your example to demonstrate.
After looking into the issue a bit closely, it apprears that this is the intended behavior as chart.js
works in just the same way (code sandbox) without react-chartjs-2
.