Blog>
Snippets

Implementing Custom Bar Chart Legends

Showcase creating custom legends for a bar chart that represent different data categories, including adding interactive elements to legends for toggling the visibility of specific bars in the chart.
import React, { useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts';
Import necessary components from the Recharts library.
const CustomLegend = ({ payload, onClick }) => (
  <ul>
    {payload.map((entry, index) => (
      <li
        key={`item-${index}`}
        onClick={() => onClick(entry.value)}
        style={{ color: entry.color, cursor: 'pointer' }}
      >
        {entry.value}
      </li>
    ))}
  </ul>
);
Define a custom legend component that allows toggling the visibility of bars.
const MyBarChart = ({ data }) => {
  const [activeBars, setActiveBars] = useState(data.map(d => d.name));

  const toggleBar = (name) => {
    setActiveBars(activeBars.includes(name)
      ? activeBars.filter(n => n !== name)
      : [...activeBars, name]
    );
  };

  return (
    <BarChart width={730} height={250} data={data}>
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip />
      {data.map(d => (
        activeBars.includes(d.name) && <Bar dataKey={d.name} fill={d.fill} />
      ))}
      <CustomLegend payload={data.map(d => ({ value: d.name, color: d.fill }))} onClick={toggleBar} />
    </BarChart>
  );
};
Use the CustomLegend and a toggle functionality within a BarChart component to allow users to hide or show bars by clicking on the legend items.