Search code examples
javascriptreactjschart.jsreact-chartjs

Showing 'undefined%' in the graph if data does not exist


I have this graph and for data that does not exist, it will show "undefined%". enter image description here

How can I get rid of the "undefined%" and just show nothing in the graph if data does not exist?

Below are the codes:

import { Bar } from "react-chartjs-2";

import "chartjs-plugin-datalabels";
import { Chart } from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";

Chart.register(ChartDataLabels);


 <Bar
          data={{
            labels,
            datasets: //datasets here
          }}
          options={{
            scales: {
              y: {
                min: 0,
                max: 100,
                ticks: {
                  stepSize: 20,
                  callback: function (value) {
                    return ((value / this.max) * 100).toFixed(0) + "%"; 
                  },
                },
              },
            },
            plugins: {
              tooltip: {
                callbacks: {
                  label: function (context) {
                    var label = context.dataset.label || "";
                    if (context.parsed.y !== null) {
                      label += " " + context.parsed.y + "%";
                    }
                    return label;
                  },
                },
              },
              datalabels: {
                formatter: (val, context) => `${val}%`,
              }, // for the label percentage symbol inside the graph
            },
          }}
        />

Solution

  • You can check if val exists using if statements

    datalabels: {
        formatter: (val, context) => {
            if(val) return `${val}%`
            return;
        },
      }, //