Skip to content

shadcn.io is an independent project built on shadcn/ui

Free

A pie chart with a custom label for React

Each slice's visitor count is drawn as text beside it, in the foreground color, with the usual label lines turned off.

Each slice's visitor count is drawn beside it as text, in the foreground color. The usual label lines are off.

Use a custom label when the default one does not say what you need. A legend covers names, and a Table covers a longer list. In React, Base UI does not draw this text. The label function in the demo does.

Preview

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.
Use email insteadNo credit card

Anatomy

Chart anatomy: container, grid, axis, bar, tooltip, legend

Usage

<div className="w-full max-w-xl rounded-md border bg-background p-4">
  <ChartContainer
    className="mx-auto aspect-square max-h-[250px] px-0"
    config={chartConfig}
  >
    <PieChart>
      <ChartTooltip
        content={<ChartTooltipContent hideLabel nameKey="visitors" />}
      />
      <Pie
        data={chartData}
        dataKey="visitors"
        label={renderLabel}
        labelLine={false}
        nameKey="browser"
      />
    </PieChart>
  </ChartContainer>
</div>

FAQ

How is the number beside each slice drawn?

Pie sets label to renderLabel and labelLine to false. renderLabel returns an SVG text at the x and y it receives, copying textAnchor and dominantBaseline, and the text is payload.visitors.

How is that text colored?

The text element uses className fill-foreground. ChartContainer is mx-auto aspect-square max-h-[250px] with px-0, which leaves the side labels the width of the frame.

What do dataKey and nameKey do here?

dataKey is visitors, so the slice angle and the printed number are the visitor count. nameKey is browser, which is the slice name passed through to the chart.

What does the tooltip call each slice?

ChartTooltipContent sets hideLabel and nameKey to visitors. That key is labeled Visitors in config, so the tooltip row uses that name and the visitor count.

How are the slices colored?

Each row sets fill to var(--color-chrome) or the matching browser variable. config maps chrome through other to --chart-1 through --chart-5 and to labels Chrome, Safari, Firefox, Edge, and Other.

Which numbers appear beside the slices?

Chrome is 275, Safari 200, Firefox 187, Edge 173, and Other 90. labelLine is false, so those numbers sit at the label position with no connector.

API Reference

Chart

Sets config={chartConfig}, hideLabel and nameKey="visitors". The rest is on the Chart page.