Skip to content
HooksPro

useChartLegend

Keeps track of which series a chart legend has switched off.

Give it the chart's series and pass to the chart's , to the card's and to its . A ChartCard with two or more series already does this on its own; reach for the hook when the legend and the chart live apart, or when other parts of the page need to know which series are visible.

See alsoChart CardLine Chart

Import

tsx
import { useChartLegend } from "@wunderui/react/charts"

Comes with WunderUI Core and Pro, in the entry of the package from your plan. See the plans.

Signature

ts
useChartLegend(series: readonly ChartSeries[], initialHidden?: readonly string[]): { hidden: string[]; toggle: (key: string) => void; items: ChartLegendItem[]; }

Parameters

ParameterTypeDefault
seriesreadonly ChartSeries[]—
initialHidden?readonly string[][]

Returns

FieldType
hiddenstring[]
toggle(key: string) => void
itemsChartLegendItem[]

Examples

A legend outside the card

tsx
import { ChartLegend, LineChart, useChartLegend } from "@wunderui/react/charts"

const series = [
  { key: "revenue", label: "Revenue", color: "indigo" },
  { key: "costs", label: "Costs", color: "orange" },
]

export function RevenueVsCosts({ data }: { data: { month: string; revenue: number; costs: number }[] }) {
  const legend = useChartLegend(series)
  return (
    <div className="flex flex-col gap-4">
      <ChartLegend items={legend.items} hiddenSeries={legend.hidden} onToggle={legend.toggle} />
      <LineChart data={data} index="month" series={series} hiddenSeries={legend.hidden} label="Revenue and costs" />
    </div>
  )
}

Start with a series switched off

tsx
const legend = useChartLegend(series, ["costs"])

<ChartCard title="Revenue" legend={legend.items} hiddenSeries={legend.hidden} onLegendToggle={legend.toggle}>
  <LineChart data={data} index="month" series={series} hiddenSeries={legend.hidden} label="Revenue and costs" />
</ChartCard>

Notes

  • The last visible series cannot be switched off, so the chart never ends up empty.
  • Keys match either the series or its , so a legend built from labels works too.
  • Each badge is a toggle button with ; a switched-off badge shows its label one step lighter and its dot dimmed.
  • One series needs no legend toggle: ChartCard shows a plain badge then.