[Chartjs]-How to custom legend with react-chartjs-2

1👍

You need to use htmlLegend if you want to render Customized Legend.

You can define plugin itself in a Pie plugins(as shown in code)or in Chart Configuration as shown in Chartjs 3x Documentation.


 htmlLegendPlugin = {
 id: "htmlLegend",
 afterUpdate(chart) {
   const items = chart.options.plugins.legend.labels.generateLabels(chart);
   const ul = document.createElement("ul");
   items.forEach(item => {
     const li = document.createElement("li");
     const boxSpan = document.createElement("span");
     boxSpan.style.background = item.fillStyle;
     li.appendChild(boxSpan);
     li.appendChild(document.createTextNode(item.text));
     ul.appendChild(li);
   });
   const jsLegend = document.getElementById("js-legend");
   jsLegend.appendChild(ul);
 }
};
<Pie data={data}
     options={option}
     height={400}
     redraw={true}
     plugins={[this.htmlLegendPlugin]}
/>
<div id='js-legend' className='whatever you wanna add'></div>

by this way your you can add custom css also to your legends.

P.S this is using React-chartjs-2.

Leave a comment