JimmyTheCode
JimmyTheCode

Reputation: 5694

How to always show a label in ChartJS in React

I'm trying to have my data points on a line graph to always show a value. Like this:

enter image description here

I've found a solution that works on ChartJS vanilla, but can't figure out how to use ChartJS with React (using functional components preferably).

So far I've got a simple chart working as follows:

import React from 'react'
import { Line } from 'react-chartjs-2'

const dataForGraph = () => {
    return {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            data: [65, 59, 80, 81, 56, 55, 40]
        }]
    }
}

export default function LineChart() {

    const data = (canvas) => {
        const ctx = canvas.getContext("2d")
        return dataForGraph()
    }

    var options = {
    }

    return (
        <Line
            data={data}
            options={options}
        >
        </Line>
    )
}

Does anyone know where to go from here?

Upvotes: 1

Views: 4228

Answers (2)

Saravana K Telapolu
Saravana K Telapolu

Reputation: 11

I was having trouble to have the labels show up with 2.0.0 version of plugin and v3 of react-chartjs-2 until I found that we need to explicit registration of plugin in someway (specific charts or global) since version v1 of the plugin.

https://v2_0_0--chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#integration

Registration: Since version 1.x, this plugin no longer registers itself automatically. It must be manually registered either globally or locally

import ChartDataLabels from 'chartjs-plugin-datalabels';

// Register the plugin to all charts:
Chart.register(ChartDataLabels);

// OR only to specific charts:
var chart = new Chart(ctx, {
  plugins: [ChartDataLabels],
  options: {
    // ...
  }
})

Upvotes: 1

JimmyTheCode
JimmyTheCode

Reputation: 5694

OK, so in the absence of figuring out how to use the vanilla method in the above, I found that the datalabels plugin is a really handy tool to achieve this.

All you have to do is run npm install chartjs-plugin-datalabels --save

Then add to your component .js file: import 'chartjs-plugin-datalabels';

And that's all you need to get this: enter image description here

There's a great example on codesandbox that I found that demonstrates how to change the label content and formatting. It's for a bar chart - but I didn't find it difficult to transfer the code to my line chart.

Upvotes: 0

Related Questions