Chart
Lightweight SVG charts: BarChart (view bars, transform-grow), AreaChart (line + fill with draw-on stroke), DonutChart (sweep segments with center label). Shared { label, value } data shape, image-role a11y summaries, reduced-motion safe.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add chartSource files
Expand a file to read the source the installer copies into your app.
components/ui/chart/Chart.tsx
import * as React from 'react'
import { Text, View, type ViewProps } from 'react-native'
import Svg, { Circle, G, Line, Path } from 'react-native-svg'
import Animated, {
Easing,
useAnimatedProps,
useAnimatedStyle,
useReducedMotion,
useSharedValue,
withDelay,
withTiming,
type SharedValue,
} from 'react-native-reanimated'
import { cn } from '@/lib/utils'
import { motionDurations } from '@/lib/motion'
import { useThemeColors } from '@/lib/theme'
/** One chart point. Labels name the category for axes and screen readers. */
export interface ChartDatum {
label: string
value: number
}
/** Default segment palette (chart token hex values). Pass `colors` to
* DonutChart to override — e.g. with the dark-mode token values. */
export const chartPalette = ['#0d9488', '#2563eb', '#d97706', '#7c3aed', '#e11d48'] as const
const AnimatedPath = Animated.createAnimatedComponent(Path)
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
function summarize(kind: string, data: ChartDatum[]): string {
if (data.length === 0) return `${kind} chart, no data`
const parts = data.slice(0, 6).map((d) => `${d.label} ${d.value}`)
return `${kind} chart: ${parts.join(', ')}${data.length > 6 ? `, and ${data.length - 6} more` : ''}`
}
/** 0→1 sweep shared by every chart. Re-runs when the data identity changes;
* static under reduced motion. All consumers animate transform, opacity, or
* stroke dash only — never layout — so charts stay at display refresh. */
function useSweep(data: ChartDatum[]): SharedValue<number> {
const reduced = useReducedMotion()
const progress = useSharedValue(reduced ? 1 : 0)
React.useEffect(() => {
progress.value = reduced
? 1
: withTiming(1, { duration: motionDurations.slow * 2, easing: Easing.out(Easing.cubic) })
}, [data, reduced, progress])
return progress
}
function EmptyChart({ height, label }: { height: number; label: string }) {
return (
<View style={{ height }} className="items-center justify-center" accessibilityLabel={label}>
<Text className="text-sm text-muted-foreground">No data yet</Text>
</View>
)
}
/* ------------------------------------------------------------------ */
/* BarChart */
/* ------------------------------------------------------------------ */
export interface BarChartProps extends ViewProps {
data: ChartDatum[]
className?: string
barClassName?: string
height?: number
showLabels?: boolean
}
function Bar({ height, index, className }: { height: number; index: number; className?: string }) {
const reduced = useReducedMotion()
const scale = useSharedValue(reduced ? 1 : 0)
React.useEffect(() => {
scale.value = reduced
? 1
: withDelay(
index * 40,
withTiming(1, { duration: motionDurations.slow + 150, easing: Easing.out(Easing.cubic) }),
)
}, [index, reduced, scale])
const grow = useAnimatedStyle(() => ({ transform: [{ scaleY: scale.value }] }))
// Keep the animated transform out of NativeWind's style resolution.
return (
<Animated.View cssInterop={false} style={[{ height, transformOrigin: 'bottom' }, grow]}>
<View className={cn('bg-chart-2 flex-1 rounded-t-[4px]', className)} />
</Animated.View>
)
}
/** Vertical bars scaled to the largest value. Bars grow from the baseline
* with a 40ms stagger (transform only). */
function BarChart({
data,
className,
barClassName,
height = 160,
showLabels = true,
accessibilityLabel,
...props
}: BarChartProps) {
const label = accessibilityLabel ?? summarize('Bar', data)
const max = Math.max(...data.map((d) => d.value), 0)
if (data.length === 0 || max <= 0) return <EmptyChart height={height} label={label} />
return (
<View accessibilityRole="image" accessibilityLabel={label} className={className} {...props}>
<View style={{ height }} className="flex-row items-end gap-2">
{data.map((d, index) => (
<View key={`${d.label}-${index}`} className="flex-1">
<Bar
height={height * Math.max(d.value / max, d.value > 0 ? 0.015 : 0)}
index={index}
className={barClassName}
/>
</View>
))}
</View>
<View className="h-px bg-border" />
{showLabels ? (
<View className="flex-row gap-2 pt-2">
{data.map((d, index) => (
<Text
key={`${d.label}-${index}`}
numberOfLines={1}
className="flex-1 text-center text-xs text-muted-foreground"
>
{d.label}
</Text>
))}
</View>
) : null}
</View>
)
}
/* ------------------------------------------------------------------ */
/* AreaChart */
/* ------------------------------------------------------------------ */
export interface AreaChartProps extends ViewProps {
data: ChartDatum[]
/** Raw stroke/fill color (SVG cannot read utility classes). Defaults to
* the theme foreground; pass a chart token hex for a colored series. */
color?: string
className?: string
height?: number
showLabels?: boolean
}
const AREA_W = 300
const AREA_H = 100
const AREA_INSET = 5
/** Line + filled area from a zero baseline, with hairline grid rows. The
* line draws on via stroke-dash offset; the fill fades in under it. */
function AreaChart({
data,
color,
className,
height = 160,
showLabels = true,
accessibilityLabel,
...props
}: AreaChartProps) {
const colors = useThemeColors()
const stroke = color ?? colors.foreground
const progress = useSweep(data)
const label = accessibilityLabel ?? summarize('Area', data)
const max = Math.max(...data.map((d) => d.value), 0)
const points = React.useMemo(() => {
if (data.length === 0 || max <= 0) return []
return data.map((d, index) => ({
x: AREA_INSET + (index / Math.max(data.length - 1, 1)) * (AREA_W - AREA_INSET * 2),
y: AREA_H - AREA_INSET - (d.value / max) * (AREA_H - AREA_INSET * 2),
}))
}, [data, max])
const { line, area, length } = React.useMemo(() => {
if (points.length === 0) return { line: '', area: '', length: 0 }
const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ')
const last = points[points.length - 1]
const first = points[0]
let total = 0
for (let i = 1; i < points.length; i++) {
total += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y)
}
return { line: path, area: `${path} L ${last.x} ${AREA_H} L ${first.x} ${AREA_H} Z`, length: total }
}, [points])
const lineProps = useAnimatedProps(() => ({ strokeDashoffset: length * (1 - progress.value) }))
const areaProps = useAnimatedProps(() => ({ opacity: 0.12 * progress.value }))
if (data.length === 0 || max <= 0) return <EmptyChart height={height} label={label} />
const firstLabel = data[0]?.label
const midLabel = data[Math.floor(data.length / 2)]?.label
const lastLabel = data[data.length - 1]?.label
const lastPoint = points[points.length - 1]
return (
<View accessibilityRole="image" accessibilityLabel={label} className={className} {...props}>
<Svg width="100%" height={height} viewBox={`0 0 ${AREA_W} ${AREA_H}`} preserveAspectRatio="none">
{[0.25, 0.5, 0.75].map((f) => (
<Line
key={f}
x1={AREA_INSET}
x2={AREA_W - AREA_INSET}
y1={AREA_H * f}
y2={AREA_H * f}
stroke={colors.input}
strokeWidth={0.75}
/>
))}
<AnimatedPath d={area} fill={stroke} stroke="none" animatedProps={areaProps} />
<AnimatedPath
d={line}
fill="none"
stroke={stroke}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
strokeDasharray={`${length}`}
animatedProps={lineProps}
/>
{points.map((p, i) => (
<Circle key={i} cx={p.x} cy={p.y} r={i === points.length - 1 ? 3.2 : 1.8} fill={stroke} />
))}
{lastPoint ? <Circle cx={lastPoint.x} cy={lastPoint.y} r={5.5} fill={stroke} opacity={0.18} /> : null}
</Svg>
{showLabels ? (
<View className="flex-row items-center justify-between pt-2">
<Text className="text-xs text-muted-foreground">{firstLabel}</Text>
<Text className="text-xs text-muted-foreground">{midLabel}</Text>
<Text className="text-xs text-muted-foreground">{lastLabel}</Text>
</View>
) : null}
</View>
)
}
/* ------------------------------------------------------------------ */
/* DonutChart */
/* ------------------------------------------------------------------ */
export interface DonutChartProps extends ViewProps {
data: ChartDatum[]
/** Segment colors (raw SVG strokes), cycled in data order. */
colors?: string[]
className?: string
size?: number
thickness?: number
centerValue?: string
centerLabel?: string
}
function DonutSegment({
progress,
size,
radius,
thickness,
circumference,
length,
offset,
stroke,
}: {
progress: SharedValue<number>
size: number
radius: number
thickness: number
circumference: number
length: number
offset: number
stroke: string
}) {
const animatedProps = useAnimatedProps(() => ({
strokeDasharray: `${Math.max(length * progress.value, 0)} ${circumference}`,
strokeDashoffset: -offset * progress.value,
}))
return (
<AnimatedCircle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke={stroke}
strokeWidth={thickness}
animatedProps={animatedProps}
/>
)
}
/** Proportional ring segments sweeping in together from the top. Render
* your own legend rows beside it — the chart stays rendering-only. */
function DonutChart({
data,
colors: palette,
className,
size = 168,
thickness = 22,
centerValue,
centerLabel,
accessibilityLabel,
...props
}: DonutChartProps) {
const colors = useThemeColors()
const progress = useSweep(data)
const label = accessibilityLabel ?? summarize('Donut', data)
const total = data.reduce((sum, d) => sum + Math.max(d.value, 0), 0)
if (data.length === 0 || total <= 0) return <EmptyChart height={size} label={label} />
const radius = (size - thickness) / 2
const circumference = 2 * Math.PI * radius
const gap = data.length > 1 ? 2.5 : 0
let cursor = 0
const segments = data.map((d, index) => {
const length = (Math.max(d.value, 0) / total) * circumference
const segment = { key: `${d.label}-${index}`, length: Math.max(length - gap, 0), offset: cursor, index }
cursor += length
return segment
})
return (
<View
accessibilityRole="image"
accessibilityLabel={label}
style={{ width: size, height: size }}
className={cn('relative', className)}
{...props}
>
<Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
<Circle cx={size / 2} cy={size / 2} r={radius} fill="none" stroke={colors.input} strokeWidth={thickness} />
<G transform={`rotate(-90 ${size / 2} ${size / 2})`}>
{segments.map((s) => (
<DonutSegment
key={s.key}
progress={progress}
size={size}
radius={radius}
thickness={thickness}
circumference={circumference}
length={s.length}
offset={s.offset}
stroke={(palette ?? chartPalette)[s.index % (palette ?? chartPalette).length]}
/>
))}
</G>
</Svg>
{centerValue || centerLabel ? (
<View className="absolute inset-0 items-center justify-center" pointerEvents="none">
{centerValue ? <Text className="text-xl font-semibold text-foreground">{centerValue}</Text> : null}
{centerLabel ? <Text className="text-xs text-muted-foreground">{centerLabel}</Text> : null}
</View>
) : null}
</View>
)
}
export { AreaChart, BarChart, DonutChart }
components/ui/chart/index.ts
export {
AreaChart,
BarChart,
DonutChart,
chartPalette,
type AreaChartProps,
type BarChartProps,
type ChartDatum,
type DonutChartProps,
} from './Chart'
Dependencies
Registry items
npm packages
react-native-reanimatedreact-native-svg