Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Chart examples · Bar

An interactive bar chart for React

A bar chart of three months of daily page views with dates on the axis and in the tooltip.

Framework
UI library

Use it for daily data over weeks or months. Three months of daily page views are bars at a fixed height, minTickGap keeps the date ticks apart, and the tooltip shows the full date. The series on show is set by one constant.

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.

FAQ

How do I switch the chart to mobile?

activeChart is "desktop". Set it to "mobile". Bar uses dataKey={activeChart} and a fill of var(--color- plus that key, so the series and the color follow the constant. config maps desktop to var(--chart-2) and mobile to var(--chart-1).

Why does the tooltip say Page Views?

ChartTooltipContent sets nameKey="views". That looks up the views entry in config, whose label is Page Views, and uses it as the row name for whichever series is drawn.

Why does the tooltip include the year when the axis doesn't?

XAxis uses tickFormatter={formatDateTick}, a short month and day, and minTickGap={32} so daily labels stay 32 pixels apart. labelFormatter is formatDateLabel, which adds year: "numeric", so the tooltip title reads like Apr 1, 2024. The tooltip also sets className to a fixed w-[150px].

How is the height fixed?

ChartContainer sets aspect-auto h-[250px] w-full. aspect-auto clears the default 16:9 box so h-[250px] holds, and the width follows the max-w-xl frame. CartesianGrid sets vertical={false}.

Does a hover highlight the bar?

Yes. This ChartTooltip doesn't set cursor to false, so the bar chart keeps its default cursor on the hovered bar. BarChart sets accessibilityLayer, and the margin is left: 12 and right: 12.

What is one row of the data?

Each chartData row has a date like 2024-04-01, plus desktop and mobile. XAxis reads dataKey="date". Only activeChart is passed to Bar, so the other number stays in the row and off the chart.