3

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;

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • I suggest starting by confirming the version of react-chartjs-2 you're using, as in your last question. Your code is compatible with react-chartjs-2 v2, but the version of it you're using in the sandbox is v3. – toki Dec 15 '21 at 22:01
  • I have checked but cannot implement it properly. –  Dec 15 '21 at 23:44

1 Answers1

3

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.

toki
  • 936
  • 5
  • 18