# Sparkline Stats

> Stat cards that pair a current value with a tiny inline trend chart. Use it to show a number and its recent direction together on a dashboard view.

A shadcn/ui block from the [@shadcn-ui-blocks](https://www.shadcn-ui-blocks.com) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/shadcn-ui-blocks/marketing-stats-sparkline-stats).

- Page, with a live preview: https://shadcn.exchange/r/shadcn-ui-blocks/marketing-stats-sparkline-stats
- Screenshot: https://abzjhwgwpdpz7ua5.public.blob.vercel-storage.com/shots/shadcn-ui-blocks/marketing-stats-sparkline-stats-light-8edd4638e15e04e1.png
- Registry item: https://www.shadcn-ui-blocks.com/r/marketing-stats-sparkline-stats.json
- Listed: 2026-10-13, source last changed 2026-10-13

## Install

```bash
npx shadcn@latest add https://www.shadcn-ui-blocks.com/r/marketing-stats-sparkline-stats.json
```

Run it in a project that has shadcn/ui set up. It adds the files below and installs what they depend on.

## Dependencies

- npm packages: `class-variance-authority`, `lucide-react`, `radix-ui`

## Files

### `components/blocks/marketing/stats/sparkline-stats.tsx`

```tsx
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { useState } from 'react';

type TimeRange = 'daily' | 'weekly' | 'monthly' | 'quarterly';

type SparklineData = {
  id: string;
  name: string;
  value: string;
  secondaryValue: string;
  change: number;
  trend: 'up' | 'down' | 'neutral';
  sparklineData: number[];
};

type SparklineStats = {
  [key in TimeRange]: SparklineData[];
};

export default function SparklineStats() {
  const [timeRange, setTimeRange] = useState<TimeRange>('monthly');

  // Sample data for different time ranges
  const stats: SparklineStats = {
    daily: [
      {
        id: 'visitors',
        name: 'Unique Visitors',
        value: '8,492',
        secondaryValue: '+1,204',
        change: 16.5,
        trend: 'up',
        sparklineData: [32, 38, 28, 43, 36, 42, 39, 37, 41, 38, 42, 48, 52, 47],
      },
      {
        id: 'page-views',
        name: 'Page Views',
        value: '32,591',
        secondaryValue: '+4,882',
        change: 17.6,
        trend: 'up',
        sparklineData: [
          142, 128, 132, 156, 148, 163, 157, 152, 166, 171, 168, 182, 190, 196,
        ],
      },
      {
        id: 'bounce-rate',
        name: 'Bounce Rate',
        value: '36.4%',
        secondaryValue: '-2.3%',
        change: -5.9,
        trend: 'down',
        sparklineData: [42, 40, 41, 39, 38, 40, 37, 36, 35, 38, 37, 34, 36, 35],
      },
      {
        id: 'orders',
        name: 'Orders',
        value: '284',
        secondaryValue: '+42',
        change: 17.4,
        trend: 'up',
        sparklineData: [18, 22, 19, 24, 21, 20, 25, 18, 24, 22, 26, 28, 27, 32],
      },
    ],
    weekly: [
      {
        id: 'visitors',
        name: 'Unique Visitors',
        value: '52,846',
        secondaryValue: '+8,294',
        change: 18.6,
        trend: 'up',
        sparklineData: [321, 384, 428, 461, 423, 462, 478, 512],
      },
      {
        id: 'page-views',
        name: 'Page Views',
        value: '198,432',
        secondaryValue: '+24,781',
        change: 14.3,
        trend: 'up',
        sparklineData: [1428, 1562, 1679, 1781, 1823, 1942, 2018, 2156],
      },
      {
        id: 'bounce-rate',
        name: 'Bounce Rate',
        value: '38.2%',
        secondaryValue: '-1.7%',
        change: -4.3,
        trend: 'down',
        sparklineData: [42, 41, 40, 39, 38, 37, 37, 36],
      },
      {
        id: 'orders',
        name: 'Orders',
        value: '1,784',
        secondaryValue: '+286',
        change: 19.1,
        trend: 'up',
        sparklineData: [176, 186, 204, 211, 234, 242, 262, 281],
      },
    ],
    monthly: [
      {
        id: 'visitors',
        name: 'Unique Visitors',
        value: '214,283',
        secondaryValue: '+32,941',
        change: 18.2,
        trend: 'up',
        sparklineData: [
          14283, 16421, 18642, 19846, 21256, 23841, 25174, 27428, 29152, 30841,
          32145, 35462,
        ],
      },
      {
        id: 'page-views',
        name: 'Page Views',
        value: '842,156',
        secondaryValue: '+72,184',
        change: 9.4,
        trend: 'up',
        sparklineData: [
          64215, 68420, 70156, 72841, 75621, 79421, 82156, 85214, 87951, 89214,
          92451, 96214,
        ],
      },
      {
        id: 'bounce-rate',
        name: 'Bounce Rate',
        value: '41.2%',
        secondaryValue: '-3.8%',
        change: -8.4,
        trend: 'down',
        sparklineData: [48, 47, 46, 46, 45, 44, 44, 43, 42, 42, 41, 40],
      },
      {
        id: 'orders',
        name: 'Orders',
        value: '7,842',
        secondaryValue: '+1,241',
        change: 18.8,
        trend: 'up',
        sparklineData: [
          524, 584, 612, 645, 687, 721, 764, 802, 852, 894, 932, 984,
        ],
      },
    ],
    quarterly: [
      {
        id: 'visitors',
        name: 'Unique Visitors',
        value: '643,294',
        secondaryValue: '+89,214',
        change: 16.1,
        trend: 'up',
        sparklineData: [154283, 182846, 214283, 246512],
      },
      {
        id: 'page-views',
        name: 'Page Views',
        value: '2,471,582',
        secondaryValue: '+210,452',
        change: 9.3,
        trend: 'up',
        sparklineData: [582416, 624185, 742156, 824582],
      },
      {
        id: 'bounce-rate',
        name: 'Bounce Rate',
        value: '43.7%',
        secondaryValue: '-5.2%',
        change: -10.6,
        trend: 'down',
        sparklineData: [52, 49, 47, 44],
      },
      {
        id: 'orders',
        name: 'Orders',
        value: '23,485',
        secondaryValue: '+3,624',
        change: 18.2,
        trend: 'up',
        sparklineData: [4856, 5742, 6254, 7412],
      },
    ],
  };

  // Function to normalize sparkline data for rendering
  const normalizeSparklineData = (data: number[]) => {
    const min = Math.min(...data);
    const max = Math.max(...data);
    const range = max - min;

    if (range === 0) return data.map(() => 50); // Handle flat data

    // Normalize to 0-100 range for SVG path
    return data.map((value) => Math.round(((value - min) / range) * 100));
  };

  // Create SVG path for sparkline
  const createSparklinePath = (data: number[]) => {
    if (data.length < 2) return '';

    const normalizedData = normalizeSparklineData(data);
    const height = 40; // SVG height
    const width = 120; // SVG width
    const points = normalizedData.map((value, index) => {
      const x = (index / (normalizedData.length - 1)) * width;
      const y = height - (value / 100) * height;
      return `${x},${y}`;
    });

    // Start from the bottom left for fill effect
    return `M0,${height} ${points
      .map((point) => `L${point}`)
      .join(' ')} L${width},${height} Z`;
  };

  // Get appropriate color for trend
  const getTrendColor = (
    trend: 'up' | 'down' | 'neutral',
    negative: boolean = false
  ) => {
    if (trend === 'up') {
      return negative
        ? 'text-rose-500 fill-rose-100 dark:fill-rose-950'
        : 'text-emerald-500 fill-emerald-100 dark:fill-emerald-950';
    } else if (trend === 'down') {
      return negative
        ? 'text-emerald-500 fill-emerald-100 dark:fill-emerald-950'
        : 'text-rose-500 fill-rose-100 dark:fill-rose-950';
    }
    return 'text-gray-500 fill-gray-100 dark:fill-gray-900';
  };

  // Bounce rate is inverted (down is good)
  const isInverseMetric = (id: string) => {
    return ['bounce-rate'].includes(id);
  };

  return (
    <div className="container mx-auto px-4 py-24 md:px-6 lg:py-32 2xl:max-w-[1400px]">
      <div className="mx-auto max-w-6xl">
        <div className="mb-12 text-center">
          <Badge className="mb-2">Analytics</Badge>
          <h2 className="text-3xl font-bold md:text-4xl">Performance Trends</h2>
          <p className="text-muted-foreground mx-auto mt-3 max-w-2xl">
            Track how our key metrics are trending over time
          </p>
        </div>

        {/* Time Range Selector - Tabs for md+ screens */}
        <div className="mb-10 flex justify-center">
          {/* Tabs for md+ screens */}
          <div className="bg-card hidden overflow-hidden rounded-lg border p-1 md:inline-flex">
            {(['daily', 'weekly', 'monthly', 'quarterly'] as TimeRange[]).map(
              (range) => (
                <button
                  key={range}
                  onClick={() => setTimeRange(range)}
                  className={cn(
                    'rounded-md px-4 py-2 text-sm font-medium transition-colors',
                    timeRange === range
                      ? 'bg-primary text-primary-foreground'
                      : 'text-muted-foreground hover:bg-muted'
                  )}
                >
                  {range.charAt(0).toUpperCase() + range.slice(1)}
                </button>
              )
            )}
          </div>

          {/* Dropdown for small screens */}
          <div className="w-full max-w-xs md:hidden">
            <Select
              value={timeRange}
              onValueChange={(value) => setTimeRange(value as TimeRange)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select time range">
                  {timeRange.charAt(0).toUpperCase() + timeRange.slice(1)}
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {(
                  ['daily', 'weekly', 'monthly', 'quarterly'] as TimeRange[]
                ).map((range) => (
                  <SelectItem key={range} value={range}>
                    {range.charAt(0).toUpperCase() + range.slice(1)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Sparkline Cards */}
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
          {stats[timeRange].map((stat) => {
            const inverse = isInverseMetric(stat.id);
            return (
              <Card key={stat.id} className="overflow-hidden">
                <CardHeader className="pb-2">
                  <CardTitle className="text-base font-medium">
                    {stat.name}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="mb-1 flex items-baseline justify-between">
                    <div className="text-2xl font-bold">{stat.value}</div>
                    <div
                      className={cn(
                        'text-sm font-medium',
                        getTrendColor(stat.trend, inverse)
                      )}
                    >
                      {stat.secondaryValue}
                    </div>
                  </div>

                  <div className="text-muted-foreground mb-4 text-xs">
                    <span className={cn(getTrendColor(stat.trend, inverse))}>
                      {stat.trend === 'up' ? '↑' : '↓'} {Math.abs(stat.change)}%
                    </span>
                    {' vs '}
                    {timeRange === 'daily' && 'yesterday'}
                    {timeRange === 'weekly' && 'last week'}
                    {timeRange === 'monthly' && 'last month'}
                    {timeRange === 'quarterly' && 'last quarter'}
                  </div>

                  {/* Sparkline */}
                  <div className="h-10 w-full">
                    <svg
                      width="100%"
                      height="40"
                      viewBox="0 0 120 40"
                      preserveAspectRatio="none"
                      className="overflow-visible"
                    >
                      <path
                        d={createSparklinePath(stat.sparklineData)}
                        className={cn(
                          'fill-current stroke-current stroke-2 opacity-10',
                          getTrendColor(stat.trend, inverse)
                        )}
                      />
                      <path
                        d={
                          createSparklinePath(stat.sparklineData).split(' Z')[0]
                        }
                        className={cn(
                          'fill-none stroke-current stroke-2',
                          getTrendColor(stat.trend, inverse)
                        )}
                      />
                    </svg>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      </div>
    </div>
  );
}
```

### `components/ui/badge.tsx`

```tsx
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"

import { cn } from "@/lib/utils"

const badgeVariants = cva(
  "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
        secondary:
          "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
        destructive:
          "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
        outline:
          "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
        ghost:
          "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
        link: "text-primary underline-offset-4 hover:underline",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

function Badge({
  className,
  variant = "default",
  asChild = false,
  ...props
}: React.ComponentProps<"span"> &
  VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
  const Comp = asChild ? Slot.Root : "span"

  return (
    <Comp
      data-slot="badge"
      data-variant={variant}
      className={cn(badgeVariants({ variant }), className)}
      {...props}
    />
  )
}

export { Badge, badgeVariants }
```

### `components/ui/card.tsx`

```tsx
import * as React from "react"

import { cn } from "@/lib/utils"

function Card({
  className,
  size = "default",
  ...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
  return (
    <div
      data-slot="card"
      data-size={size}
      className={cn(
        "group/card flex flex-col gap-6 overflow-hidden rounded-xl bg-card py-6 text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 has-[>img:first-child]:pt-0 data-[size=sm]:gap-4 data-[size=sm]:py-4 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
        className
      )}
      {...props}
    />
  )
}

function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-header"
      className={cn(
        "group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-6 group-data-[size=sm]/card:px-4 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-6 group-data-[size=sm]/card:[.border-b]:pb-4",
        className
      )}
      {...props}
    />
  )
}

function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-title"
      className={cn(
        "font-heading text-base leading-normal font-medium group-data-[size=sm]/card:text-sm",
        className
      )}
      {...props}
    />
  )
}

function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-description"
      className={cn("text-sm text-muted-foreground", className)}
      {...props}
    />
  )
}

function CardAction({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-action"
      className={cn(
        "col-start-2 row-span-2 row-start-1 self-start justify-self-end",
        className
      )}
      {...props}
    />
  )
}

function CardContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-content"
      className={cn("px-6 group-data-[size=sm]/card:px-4", className)}
      {...props}
    />
  )
}

function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="card-footer"
      className={cn(
        "flex items-center rounded-b-xl px-6 group-data-[size=sm]/card:px-4 [.border-t]:pt-6 group-data-[size=sm]/card:[.border-t]:pt-4",
        className
      )}
      {...props}
    />
  )
}

export {
  Card,
  CardHeader,
  CardFooter,
  CardTitle,
  CardAction,
  CardDescription,
  CardContent,
}
```

### `components/ui/select.tsx`

```tsx
"use client"

import * as React from "react"
import { Select as SelectPrimitive } from "radix-ui"

import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"

function Select({
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
  return <SelectPrimitive.Root data-slot="select" {...props} />
}

function SelectGroup({
  className,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
  return (
    <SelectPrimitive.Group
      data-slot="select-group"
      className={cn("scroll-my-1 p-1", className)}
      {...props}
    />
  )
}

function SelectValue({
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
  return <SelectPrimitive.Value data-slot="select-value" {...props} />
}

function SelectTrigger({
  className,
  size = "default",
  children,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
  size?: "sm" | "default"
}) {
  return (
    <SelectPrimitive.Trigger
      data-slot="select-trigger"
      data-size={size}
      className={cn(
        "flex w-fit items-center justify-between gap-1.5 rounded-md border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      {...props}
    >
      {children}
      <SelectPrimitive.Icon asChild>
        <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
      </SelectPrimitive.Icon>
    </SelectPrimitive.Trigger>
  )
}

function SelectContent({
  className,
  children,
  position = "item-aligned",
  align = "center",
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
  return (
    <SelectPrimitive.Portal>
      <SelectPrimitive.Content
        data-slot="select-content"
        data-align-trigger={position === "item-aligned"}
        className={cn("relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", position ==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )}
        position={position}
        align={align}
        {...props}
      >
        <SelectScrollUpButton />
        <SelectPrimitive.Viewport
          data-position={position}
          className={cn(
            "data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",
            position === "popper" && ""
          )}
        >
          {children}
        </SelectPrimitive.Viewport>
        <SelectScrollDownButton />
      </SelectPrimitive.Content>
    </SelectPrimitive.Portal>
  )
}

function SelectLabel({
  className,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
  return (
    <SelectPrimitive.Label
      data-slot="select-label"
      className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
      {...props}
    />
  )
}

function SelectItem({
  className,
  children,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
  return (
    <SelectPrimitive.Item
      data-slot="select-item"
      className={cn(
        "relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
        className
      )}
      {...props}
    >
      <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
        <SelectPrimitive.ItemIndicator>
          <CheckIcon className="pointer-events-none" />
        </SelectPrimitive.ItemIndicator>
      </span>
      <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
    </SelectPrimitive.Item>
  )
}

function SelectSeparator({
  className,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
  return (
    <SelectPrimitive.Separator
      data-slot="select-separator"
      className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
      {...props}
    />
  )
}

function SelectScrollUpButton({
  className,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
  return (
    <SelectPrimitive.ScrollUpButton
      data-slot="select-scroll-up-button"
      className={cn(
        "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      {...props}
    >
      <ChevronUpIcon
      />
    </SelectPrimitive.ScrollUpButton>
  )
}

function SelectScrollDownButton({
  className,
  ...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
  return (
    <SelectPrimitive.ScrollDownButton
      data-slot="select-scroll-down-button"
      className={cn(
        "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      {...props}
    >
      <ChevronDownIcon
      />
    </SelectPrimitive.ScrollDownButton>
  )
}

export {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectScrollDownButton,
  SelectScrollUpButton,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
}
```
