Search code examples
javascriptreactjschart.jsreact-chartjs-2

How to add a title in Doughnut chart chart.js React


I want to add a Title for the Doughnut chart in my React app but for some reason it doesn't work. I have this code:

const chartData = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: [
          Colors.primary,
          Colors.secondary,
          Colors.danger,
          Colors.warning
        ],
        hoverBackgroundColor: [
          'rgb(143, 0, 180, 0.3)',
          'rgb(0, 196, 204, 0.3)',
          'rgb(206, 0, 0, 0.3)',
          'rgb(255, 179, 0, 0.3)'
        ],
        hoverOffset: 10
      }]
    };

    const options = {
      responsive: true,
      legend: {
        display: false,
        position: 'right',
      },
      title: {
        display: true,
        fontSize: 20,
        text: 'Tickets'
      }
    }

        <Doughnut 
          data = { chartData } 
          options = { options }
        />

What could have gone wrong here? I also want to place the labels on the right side of the chart, but it doesn't work as well. Below is the output.

enter image description here


Solution

  • Since Chart.js version 3 title, subtitle, legend and tooltip are plugins and their options must be defined in plugins node. As far as I have seen, react-chartjs-2 is working with Chartjs version >= 3.

    const options = {
      responsive: true,
      plugins: {
        legend: {
          display: false,
          position: 'right',
        },
        title: {
          display: true,
          fontSize: 20, // <--- this is not a managed option since CHART.JS 3
          text: 'Tickets'
        }
      }
    }