glasscn
ShowcaseDocsComponentsStudioThemingNative
5Get started
Guides
IntroductionInstallationThemingFonts & typeStudioReact Native
Surfaces
AuroraBackdropGlassLiquid glassCardTheme scopeBackground extensionScroll areaAccordionCollapsibleAlertItemEmpty
Typography
TypographyProse
Controls
ButtonBadgeInputTextareaLabelSwitchCheckboxSegmented controlTabsGlass groupGlass clusterGlass morphSliderProgressKbdSeparatorAvatarGlass preferencesComboboxCalendarDate pickerSpinnerSkeletonSelectRadio groupFieldInput groupButton groupToggleToggle groupStepper
Overlays
DialogAlert dialogSheetAction sheetPopoverTooltipDropdown menuToasterCommandDrawerContext menuConfirmation popover
Navigation
DockToolbarScroll edgeNavigation barSidebarSearch fieldGrouped list
Data
Activity ringsProgress ringSparklineStatKPIWidgetRange chartBar listGaugeTrackerCategory barHeatmapChartArea chartBar chartLine chartDonut chartTableData table
Chat
ChatChat markdownChat parts
Blocks
More Apple glass examplesLiquid Glass examplesDashboardAnalyticsSettingsSign inChat
glasscn — a shadcn registry. Copy it, own it, change it.DocsThemingregistry.json
Data@tanstack/charts

Line chart

Measures over time, one smooth (or stepped) line per series, with scrubbing, selection, a grouped glass tooltip and a crosshair.

Installation

pnpm dlx shadcn@latest add https://glasscn.app/r/line-chart.json

React Native (iOS, Android and web through react-native-web) — same parts and props:

pnpm dlx shadcn@latest add https://glasscn.app/r/native-line-chart.json

Or with the namespace set up: shadcn add @glasscn-app/line-chart

Props

PropTypeDefault
datareadonly Row[]

Your rows, unmodified — tooltips and callbacks get them back.

—
x(d: Row) => string | number | Date

Dates get a UTC time axis, numbers a linear one, strings evenly spaced points.

—
series{ id; label; value: (d: Row) => number | null; color?; format? }[]

One line each. null is a gap. Colours default to --chart-1…8.

—
ariaLabelstring

Required.

—
pointsboolean

A dot at each value.

false
curve"smooth" | "linear" | "step"

Smooth is monotone: it never swings past a peak.

"smooth"
onScrub(row: Row | null) => void

The row under the pointer, finger (press and drag) or keyboard focus.

—
axis"leading" | "trailing"

The value axis side — trailing, as Apple's charts (flips in RTL).

"trailing"
selectedX / onSelectx value | null / (row: Row | null) => void

Controlled selection: a click, tap or Enter on a point reports its row; selectedX marks it.

—
state / onRetry / stateLabels"ready" | "loading" | "empty" | "error"

A skeleton, "No data for this range" or an error with a retry, the plot's height.

"ready" ("empty" when data is empty)
accessibilityTableboolean | "visible"

A ChartSummary sentence and ChartDataTable for screen readers (sr-only), shown with "visible", omitted with false.

true
valueFormat / xFormat(v) => string

Axis ticks, tooltip and the data table.

—
height / legend / gridnumber / boolean / boolean240 / series > 1 / true

Hovering snaps to the nearest x and lists every series there; arrow keys move along x.

Accessors can be inline arrows: the preset keeps them stable and calls the latest. Pass new data to redraw.

Source

components/glass/line-chart.tsx
"use client"

import * as React from "react"
import { cn } from "@/lib/glass-cn"
import { defineChart, lineY, ruleX } from "@tanstack/charts"
import { crosshair } from "@tanstack/charts/crosshair"
import { tooltip } from "@tanstack/charts/tooltip"

import {
  ChartAlternative,
  ChartContainer,
  ChartLegend,
  categoryAxisStyle,
  chartColor,
  seriesTooltip,
  useAxisSide,
  useChartAccessors,
  valueAxis,
  xScaleFor,
  type ChartAccessibility,
  type ChartSeries,
  type ChartStateLabels,
  type ChartStateValue,
} from "@/components/glass/chart"
import { monotoneCurve, stepCurve } from "@/lib/glass-charts"

type XValue = string | number | Date

/**
 * Measures over an ordered x — days, weeks, sessions. One line per series over
 * your rows, unmodified; hovering (or press-and-drag on touch, arrow keys on
 * the keyboard) scrubs every series at that x in a glass tooltip. Nulls are gaps.
 */
function LineChart<Row>({
  data,
  x: xProp,
  series: seriesProp,
  ariaLabel,
  height = 240,
  valueFormat: valueFormatProp,
  xFormat: xFormatProp,
  legend = seriesProp.length > 1,
  grid = true,
  points = false,
  curve = "smooth",
  axis = "trailing",
  selectedX,
  onSelect,
  onScrub,
  state,
  onRetry,
  stateLabels,
  accessibilityTable = true,
  className,
  ...props
}: Omit<React.ComponentProps<"div">, "children" | "onSelect"> & {
  data: readonly Row[]
  x: (d: Row) => XValue
  series: readonly ChartSeries<Row>[]
  ariaLabel: string
  height?: number
  valueFormat?: (value: number) => string
  xFormat?: (value: XValue) => string
  legend?: boolean
  grid?: boolean
  points?: boolean
  curve?: "smooth" | "linear" | "step"
  /** Which side the value axis sits on. Apple's charts put it trailing. */
  axis?: "leading" | "trailing"
  /** Marks this x with a rule — controlled selection. */
  selectedX?: XValue | null
  /** A click, tap or Enter on a point selects its row; null clears. */
  onSelect?: (row: Row | null) => void
  /** The row under the pointer or keyboard focus while scrubbing; null when it leaves. */
  onScrub?: (row: Row | null) => void
  state?: ChartStateValue
  onRetry?: () => void
  stateLabels?: ChartStateLabels
  /** Exact values for assistive tech: true (sr-only, default), "visible", or false. */
  accessibilityTable?: ChartAccessibility
}) {
  const ref = React.useRef<HTMLDivElement>(null)
  const side = useAxisSide(ref, axis)
  const { x, series, valueFormat, xFormat, key } = useChartAccessors({ x: xProp, series: seriesProp, valueFormat: valueFormatProp, xFormat: xFormatProp })
  const selectedKey = selectedX == null ? null : selectedX instanceof Date ? selectedX.getTime() : selectedX
  const selectedIsDate = selectedX instanceof Date
  const definition = React.useMemo(() => {
    const path = curve === "smooth" ? monotoneCurve : curve === "step" ? stepCurve : undefined
    const selected = selectedKey == null ? [] : [selectedIsDate ? new Date(selectedKey) : selectedKey]
    return defineChart({
      marks: [
        ...series.map((s) =>
          lineY(data, {
            id: s.id,
            x,
            y: s.value,
            z: () => s.id,
            color: () => s.id,
            points,
            strokeWidth: 2.25,
            curve: path,
          })
        ),
        ...(selected.length ? [ruleX(selected, { id: "selected", stroke: "var(--foreground)", strokeOpacity: 0.4, strokeWidth: 1 })] : []),
        crosshair({ x: true, y: false }),
      ],
      scales: {
        x: { scale: xScaleFor(data.map(x), "point"), axis: categoryAxisStyle(xFormat) },
        y: valueAxis({ grid, valueFormat, side }),
      },
      color: { domain: series.map((s) => s.id), range: series.map((s, i) => s.color ?? chartColor(i)) },
      focus: "group-x",
      maxFocusDistance: Number.POSITIVE_INFINITY,
      tooltip: {
        use: tooltip,
        anchor: "group-center",
        sort: "color-domain",
        placement: ["top", "right", "left", "bottom"],
        content: seriesTooltip(series, x, { xFormat, valueFormat }),
      },
    })
    // `key` stands for the accessors' structure; they call your latest functions
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, key, grid, points, curve, side, selectedKey, selectedIsDate])

  return (
    <div ref={ref} data-slot="line-chart" className={cn("grid w-full gap-3", className)} {...props}>
      <ChartContainer
        definition={definition}
        ariaLabel={ariaLabel}
        height={height}
        state={state ?? (data.length ? "ready" : "empty")}
        onRetry={onRetry}
        stateLabels={stateLabels}
        onSelect={onSelect ? (p) => onSelect(p ? (p.datum as Row) : null) : undefined}
        onFocusChange={onScrub ? (p) => onScrub(p ? (p.datum as Row) : null) : undefined}
      />
      {legend ? <ChartLegend shape="line" items={series.map((s, i) => ({ label: s.label, color: s.color ?? chartColor(i) }))} /> : null}
      <ChartAlternative mode={accessibilityTable} data={data} x={x} series={series} xFormat={xFormat} valueFormat={valueFormat} label={ariaLabel} />
    </div>
  )
}

export { LineChart }
Bar chartDonut chart
Mood & energy
Evening check-ins, last 14 days. Tap a day to pin it.
Sep 24Sep 26Sep 28Sep 30Oct 2Oct 4Oct 64/105/106/107/108/109/10
  • Mood
  • Energy

Mood: 14 values, low 5/10, high 9/10, latest 8/10, trending up. Energy: 13 values, low 4/10, high 8/10, latest 8/10, trending up.

Mood and energy check-ins over the last 14 days, scored 1 to 10
MoodEnergy
Sep 246/105/10
Sep 257/106/10
Sep 265/104/10
Sep 276/106/10
Sep 288/107/10
Sep 298/108/10
Sep 307/106/10
Oct 16/105/10
Oct 25/10–
Oct 37/106/10
Oct 47/107/10
Oct 58/107/10
Oct 69/108/10
Oct 78/108/10