'How to custom legend with react-chartjs-2

I'm trying to create a custom legend template in chartjs v3.3.0 like the image below. I can't seem to find any documentation in v3.3.0 for this option. Is it even available anymore? Can anyone show an example of how to accomplish this?

Here is my settings:

  plugins: {
    legend: {
      display: true,
      onClick: () => {
        console.log('do nothing');
      },
      position: 'bottom',
      labels: {
        usePointStyle: true,
        pointStyle: 'circle',
        // generateLabels: (chart) => {
        //   console.log(chart.legend);
        //   return [1, 2];
        // },
      },
    },
    title: {
      text: 'Gender',
      display: true,
    },
  },
},
type: 'doughnut',
data: {
  labels: defaultColors,
  datasets: [
    {
      label: 'label1',
      data: [1, 2],
      backgroundColor: getBackground,
      borderWidth: 0,
    },
  ],
},
width: 'auto',
height: '100%',

Sample Image



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Darshak patel