React I want to add text to the react-chart-2 tooltip

Viewed 580

I am using react-chart-2.
Hover over the graph to see the tooltip. I want to display a % to the right of the number, like 30%.
How can I add the % character to the tooltip? Also, how can I set the left value to a minimum of 0 and a maximum of 100?

code

import "./styles.css";
import { Line } from "react-chartjs-2";

const App = () => {
  const data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
      {
        label: "test",
        data: [30, 10, 10, 40, 70, 10, 30],
        fill: false,
        backgroundColor: "#F7C520",
        borderColor: "#F7C520",
        hoverBackgroundColor: "#E6B71E",
        hoverBorderColor: "#E6B71E"
      }
    ]
  };

  const options = {
    responsive: true,
    tooltips: {
      mode: "label"
    },
    elements: {
      line: {
        fill: false
      }
    },
    scales: {
      xAxes: [
        {
          display: true,
          gridLines: {
            display: true
          }
        }
      ]
    }
  };

  return (
    <div className="App">
      <h2>Mixed data Example</h2>
      <Line data={data} options={options} />
    </div>
  );
};

export default App;

1 Answers

ChartJS provides a callback that allows you to customize the contents of your tooltip. ChartJS also has many other Tooltip callbacks that come in handy for customizing the look and feel of your graphs, and react-chartjs-2, being a wrapper around ChartJS, allows the same functionality.

Add a plugins object containing tooltip configuration as below:

    plugins: {
      tooltip: {
        callbacks: {
          label: (context: any) => {
            let label = "";
            if (context.parsed.y) {
              label = context.parsed.y + "%"
            }
            return label;
          }
        }
      }
    }

Resulting in:

tooltip with a percentage sign added

As for your other question, you seem to have figured it out in your sandbox already. Set the min and max values on your axis to the desired values.

Related