Search code examples
javascriptreactjstypescriptfrontendapexcharts

Toggle all data series upon clicking a legend in Apex charts


In the below chart, assume there is the fourth legend say, 'All' and when I click on it, all the data should disappear. When I click it back again, all data must re-appear. Is there a way to do it in apex charts?

enter image description here


Solution

  • Added a new button within the div where the chart is added and have an onclick action for it which will call the function toggle series

    <div className={"chart-item " + className} key={index}>
      <Chart series={option.series} options={option} height={600} />
      <div className="all-lines">
        <input
          className="button-css"
          type="button"
          value={toggleText[index]}
          onClick={(e) => {
            toggleSeries(option?.chart?.id, option?.series, e);
          }}
        />
      </div>
    </div>
    

    The toggle series function will hide or display all legends depending upon the current state of the chart.

    function toggleSeries(
          id: string | undefined,
          series: ApexAxisChartSeries | ApexNonAxisChartSeries | undefined,
          e: any
        ) {
          const functionName =
            e.target.value === hideText ? "hideSeries" : "showSeries";
          e.target.value = e.target.value === hideText ? showText : hideText;
          const chartSeries: ApexAxisChartSeries | undefined = series
            ? (series as ApexAxisChartSeries)
            : undefined;
          const chartId = id ? id : "";
    
          chartSeries?.forEach((ser) => {
            ApexCharts.exec(chartId, functionName, ser.name);
          });
        }
    
        return lineChartItems;
      }