Khaled Boussoffara
Khaled Boussoffara

Reputation: 1771

react chart js, title is not displayed

I'm using react chart js to show a doughnut in my component.

"chart.js": "^3.7.1",
"react-chartjs-2": "^4.1.0",

I'm not able to show the title :

const data = {
  labels: ["Score", "Total"],
  datasets: [
    {
      label: "Indice d'impact global de la transaction",
      data: [3.7, 5],
      backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(128,128,128,0.2)"],
      borderColor: ["rgba(54, 162, 235, 1", "rgba(128,128,128,1)"],
      borderWidth: 1,
      lineTension: 0.5,
    },
  ],
};

<Doughnut
options={{
  plugins: {
    title: {
      display: true,
      text: "Indice d'impact global de la transaction",
      align: "center",
      padding: {
        top: 10,
        bottom: 30,
      },
    },
    legend: {
      display: true,
      position: "top",
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  },
}}
data={data}
/>

How can i correclty show the title ?

enter image description here

Upvotes: 5

Views: 4161

Answers (2)

Elijah Baraza
Elijah Baraza

Reputation: 311

Use this:

a) Ensure you have installed chart.js:

npm install chart.js

b) Import Chart and Title as shown below:

import { Chart, Title } from "chart.js";

c) Register Title as show below:

Chart.register(Title);

d) Then set the title as given below:

options: {
  responsive: true,
  plugins: {
     title: {
        display: true,
        text: 'Bar Chart'
      }
   }
}

Upvotes: 0

LeeLenalee
LeeLenalee

Reputation: 31331

This is because you are using treeshaking and not importing and registering the Title

To fix it either import and registr every component you are using, list of all components can be found here like so:

import {Chart, Title} from 'chart.js';
Chart.register(Title);

Or use the auto import to let chart.js register everything for you:

import 'chart.js/auto'

Upvotes: 10

Related Questions