Skip to content
Thrum

Date range picker

Two date fields, start and end, with a range calendar and a list of presets in a popover. Use it to set the period of a report or an export. For one date use the date picker; for a range that is always on screen use the calendar in range mode.

Install

npx shadcn@latest add https://thrumui.dev/r/date-range-picker.json

Adds components/ui/date-range-picker.tsx. Nothing else in your project changes.

import { presetRange } from "@/components/ui/date-range-picker";

Automatically installs icon calendar-range from the icon set.

Data shape

Type
type DateRange = { from: Date | null; to: Date | null };
type DateRangePreset = "last-7-days" | "last-30-days" | "this-month" | "last-month" | "year-to-date";
Sample
const period: DateRange = {
  from: new Date(2026, 10, 27),
  to: new Date(2026, 11, 3),
};

Props

PropTypeDefaultDescription
valueDateRange–The range, when the parent holds it. Use it with onValueChange.
defaultValueDateRangeDefault { from: null, to: null }The range at first, when the picker holds it itself.
onValueChange(value: DateRange) => void–Called when a range is applied: both days picked, a preset chosen, Apply pressed, or a field typed in full or cleared.
minDate | null–The earliest day of a range. Earlier days cannot be picked, and presets that reach them are disabled.
maxDate | null–The latest day of a range.
maxDaysnumber–The longest range in days, both ends counted. Once a start is picked, days further away cannot be picked.
disabledDaysDate[] | { dayOfWeek: number[] }–Days that cannot start or end a range. Days between the ends may be disabled ones.
weekStartsOn0 | 1 | 2 | 3 | 4 | 5 | 6–The calendar's first column, 0 for Sunday. Defaults to the locale's week.
localestringDefault "en-US"Sets the segment order and the month and weekday names.
todayDate–Marks today, opens the calendar on its month when the range is empty, and anchors the presets. Without it there are no presets.
presetsDateRangePreset[]Default all fiveThe presets beside the calendar, in order: Last 7 days, Last 30 days, This month (the 1st to today), Last month, Year to date. [] hides the list.
confirmbooleanDefault falseHold the range in the panel until Apply is pressed; Cancel drops it. Without it the second day, or a preset, applies at once and closes the panel.
startNamestring–The form name of the start field. A hidden input submits the day as 2026-12-03.
endNamestring–The form name of the end field.
size"sm" | "md" | "lg"Default "md"sm is 28 pixels tall, md 32, lg 40. The calendar button matches it.
disabledbooleanDefault falseBoth fields and the button are dimmed and cannot be used.
soundbooleanDefault truePlay the popover's open and close sounds, and a click on each day or preset picked, if the visitor has sound on.
classNamestring–Extra classes for the root. It fills its container; at 560 pixels and wider the calendar shows two months.
presetRange(preset, today){ from: Date; to: Date }–Exported helper: the days a preset stands for, to label a report with the same range.

Motion and sound

Motion

  • The panel fades in and grows from 96% to full size over 150 ms, from the edge that touches the button.
  • Closing plays the same change backwards.
  • Reduced motion: it appears and leaves at once.

Sound

  • A soft rising tone when the panel opens, and a falling one when it closes by Escape, a press outside, Cancel or Apply.
  • A click for each day and each preset picked. A pick that applies the range closes the panel with no second sound.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • The root is a group: name it with aria-labelledby or aria-label. The fields are named Start date and End date.
  • An end before the start, a range longer than maxDays, or a day outside min and max marks the end field invalid.
  • The applied range is read once through a polite live region: Selected November 27 – December 3, 2026, 7 days.
  • The calendar button carries the same words in its name. The panel is a non-modal dialog named Choose dates.
  • The preset that matches the range carries aria-pressed and a filled background.
  • Under a glass material the panel is translucent. Its tint keeps the text at 4.5 to 1 over any page.
KeysAction
0 to 9, ↑ / ↓, ← / →In either field: type and step the segments, as in the date input.
Enter / SpaceOn the calendar button: open the panel, with the focus on the start of the range, or on today.
Arrows, Page Up / Page Down, Home / EndIn the calendar: move by day, week, month and week edge. After the first end is picked, the range follows the focus as a preview.
Enter / SpaceIn the calendar: pick the start, then the end. Without confirm the second pick applies and closes.
TabIn the panel: move between the presets, the month buttons, the grid and the footer.
EscClose the panel and keep the applied range. The focus returns to the button.

Source

components/ui/date-range-picker.tsx
"use client";

import { useRef, useState, type ComponentProps } from "react";

import { cn } from "@/lib/utils";
import { CalendarRangeIcon } from "@/components/icons/calendar-range";
import { useSize } from "@/lib/thrum-chart";
import { play } from "@/lib/thrum-sound";
import { buttonClass } from "@/components/ui/button";
import {
  addDays,
  addMonths,
  Calendar,
  compareDays,
  differenceInDays,
  endOfMonth,
  isDayDisabled,
  isSameDay,
  makeDate,
  startOfMonth,
  type DateRange,
  type DisabledDays,
  type Weekday,
} from "@/components/ui/calendar";
import { DateInput, dateError, type SegmentFieldSize } from "@/components/ui/date-input";
import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "@/components/ui/popover";

export type DateRangePreset = "last-7-days" | "last-30-days" | "this-month" | "last-month" | "year-to-date";

const PRESET_LABEL: Record<DateRangePreset, string> = {
  "last-7-days": "Last 7 days",
  "last-30-days": "Last 30 days",
  "this-month": "This month",
  "last-month": "Last month",
  "year-to-date": "Year to date",
};
const ALL_PRESETS = Object.keys(PRESET_LABEL) as DateRangePreset[];

/** The days a preset stands for, counted back from `today`, today included. "This month" runs from the 1st to today. */
export function presetRange(preset: DateRangePreset, today: Date): { from: Date; to: Date } {
  if (preset === "last-7-days") return { from: addDays(today, -6), to: today };
  if (preset === "last-30-days") return { from: addDays(today, -29), to: today };
  if (preset === "this-month") return { from: startOfMonth(today), to: today };
  if (preset === "last-month") return { from: startOfMonth(addMonths(startOfMonth(today), -1)), to: endOfMonth(addMonths(startOfMonth(today), -1)) };
  return { from: makeDate(today.getFullYear(), 0, 1), to: today };
}

const EMPTY: DateRange = { from: null, to: null };
const same = (a: DateRange, b: DateRange) => (a.from === b.from || isSameDay(a.from, b.from)) && (a.to === b.to || isSameDay(a.to, b.to));

export type DateRangePickerProps = Omit<ComponentProps<"div">, "defaultValue" | "onChange"> & {
  /** The range, when the parent holds it. Use it with onValueChange. */
  value?: DateRange;
  /** The range at first, when the picker holds it itself. */
  defaultValue?: DateRange;
  /** Called with the range when it is applied: picked, chosen from a preset, or typed into either field. */
  onValueChange?: (value: DateRange) => void;
  /** The earliest day of a range. */
  min?: Date | null;
  /** The latest day of a range. */
  max?: Date | null;
  /** The longest range, in days, both ends counted. */
  maxDays?: number;
  /** Days that cannot start or end a range: a list of dates, or `{ dayOfWeek: [0, 6] }`. */
  disabledDays?: DisabledDays;
  /** The calendar's first column: 0 is Sunday, 1 Monday. Defaults to the locale's week. */
  weekStartsOn?: Weekday;
  /** Sets the segment order and the month and day names. */
  locale?: string;
  /** Today, for the calendar's mark and the presets. The picker never reads the clock itself. */
  today?: Date;
  /** The presets in the list beside the calendar, in order. An empty list hides it. Needs `today`. */
  presets?: readonly DateRangePreset[];
  /** Hold the range in the panel until Apply is pressed; Cancel drops it. Without it, the second day applies at once. */
  confirm?: boolean;
  /** The field names in a form. Hidden inputs submit both days as 2026-12-03. */
  startName?: string;
  endName?: string;
  /** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
  size?: SegmentFieldSize;
  disabled?: boolean;
  /** Play the popover's open and close sounds and a click on each pick, if the visitor has sound on. */
  sound?: boolean;
};

/**
 * Two date fields, start and end, with a range calendar in a popover: two months side by side from 560 pixels of
 * container width, one below. Presets cover the usual reporting ranges. Name the group with `aria-label` or `aria-labelledby`.
 */
export function DateRangePicker({
  value,
  defaultValue = EMPTY,
  onValueChange,
  min,
  max,
  maxDays,
  disabledDays,
  weekStartsOn,
  locale = "en-US",
  today,
  presets = ALL_PRESETS,
  confirm = false,
  startName,
  endName,
  size = "md",
  disabled = false,
  sound = true,
  className,
  ...props
}: DateRangePickerProps) {
  const [own, setOwn] = useState<DateRange>(defaultValue);
  const range = value ?? own;
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState<DateRange>(EMPTY);
  const [month, setMonth] = useState<Date>(() => startOfMonth(range.from ?? today ?? makeDate(2000, 0, 1)));
  const [root, { width }] = useSize<HTMLDivElement>();
  const panel = useRef<HTMLDivElement>(null);
  const months = width >= 560 ? 2 : 1;

  const apply = (next: DateRange) => {
    if (same(next, range)) return;
    if (value === undefined) setOwn(next);
    onValueChange?.(next);
  };

  // Turn the calendar so that the range's end is in sight.
  const showRange = (next: DateRange) => {
    const end = next.to ?? next.from;
    if (end) setMonth(startOfMonth(addMonths(end, -(months - 1))));
  };

  const onOpenChange = (next: boolean) => {
    if (next) {
      setDraft(range);
      setMonth(startOfMonth(range.from ?? today ?? new Date()));
    }
    setOpen(next);
  };

  const pickDraft = (next: DateRange) => {
    setDraft(next);
    if (!confirm && next.from && next.to) {
      apply(next);
      setOpen(false); // the pick made its own sound: no closing sound
    }
  };

  const outOfReach = (r: { from: Date; to: Date }) =>
    isDayDisabled(r.from, { min, max, disabledDays }) || isDayDisabled(r.to, { min, max, disabledDays }) || Boolean(maxDays && differenceInDays(r.from, r.to) + 1 > maxDays);

  const long = new Intl.DateTimeFormat(locale, { day: "numeric", month: "long", year: "numeric" });
  const said = range.from && range.to ? `${long.formatRange(range.from, range.to)}, ${differenceInDays(range.from, range.to) + 1} days` : "";
  const endError =
    dateError(range.to, min, max) ??
    (range.from && range.to && compareDays(range.to, range.from) < 0 ? "before start" : null) ??
    (range.from && range.to && maxDays && differenceInDays(range.from, range.to) + 1 > maxDays ? "too long" : null);
  const shown = today ? presets : [];
  const dash = "text-muted-foreground";

  return (
    <div ref={root} data-slot="date-range-picker" role="group" className={cn("flex w-full min-w-0 flex-wrap items-center gap-1", className)} {...props}>
      <DateInput
        aria-label="Start date"
        value={range.from}
        onValueChange={(from) => apply({ ...range, from })}
        min={min}
        max={max}
        locale={locale}
        name={startName}
        size={size}
        disabled={disabled}
        className="min-w-28 flex-1 basis-28"
      />
      <span aria-hidden="true" className={dash}>
        –
      </span>
      <DateInput
        aria-label="End date"
        value={range.to}
        onValueChange={(to) => apply({ ...range, to })}
        min={min}
        max={max}
        locale={locale}
        name={endName}
        size={size}
        disabled={disabled}
        invalid={endError !== null}
        className="min-w-28 flex-1 basis-28"
      />
      <Popover open={open} onOpenChange={onOpenChange} sound={sound}>
        <PopoverTrigger
          data-slot="date-range-picker-trigger"
          data-surface="control"
          aria-label={said ? `Choose dates, ${said}` : "Choose dates"}
          disabled={disabled}
          className={cn(buttonClass({ variant: "outline", size: "icon" }), size === "sm" ? "size-7" : size === "lg" ? "size-10" : "size-8", "flex-none [&_svg]:size-4")}
        >
          <CalendarRangeIcon />
        </PopoverTrigger>
        <PopoverContent
          aria-label="Choose dates"
          align="end"
          className="w-auto max-w-(--available-width) p-3"
          initialFocus={() => panel.current?.querySelector<HTMLElement>('[data-slot="calendar-day"][tabindex="0"]') ?? true}
        >
          <div ref={panel} data-slot="date-range-picker-panel" className="flex flex-col gap-3 sm:flex-row">
            {shown.length > 0 && today && (
              <div data-slot="date-range-picker-presets" className="flex flex-wrap gap-1 sm:w-32 sm:flex-none sm:flex-col sm:border-e sm:pe-3">
                {shown.map((preset) => {
                  const r = presetRange(preset, today);
                  return (
                    <button
                      key={preset}
                      type="button"
                      aria-pressed={same(r, draft)}
                      disabled={outOfReach(r)}
                      className={cn(buttonClass({ variant: "ghost", size: "sm" }), "justify-start aria-pressed:bg-accent aria-pressed:text-accent-foreground")}
                      onClick={() => {
                        if (sound) play("select");
                        showRange(r);
                        pickDraft(r);
                      }}
                    >
                      {PRESET_LABEL[preset]}
                    </button>
                  );
                })}
              </div>
            )}
            <div className="grid gap-3">
              <Calendar
                mode="range"
                value={draft}
                onValueChange={pickDraft}
                month={month}
                onMonthChange={setMonth}
                numberOfMonths={months}
                min={min}
                max={max}
                maxDays={maxDays}
                disabledDays={disabledDays}
                weekStartsOn={weekStartsOn}
                locale={locale}
                today={today}
                sound={sound}
                surface={false}
                className="border-0 bg-transparent p-0"
              />
              {confirm && (
                <div data-slot="date-range-picker-footer" className="flex justify-end gap-2 border-t pt-3">
                  <PopoverClose className={buttonClass({ variant: "outline", size: "sm" })}>Cancel</PopoverClose>
                  <PopoverClose className={buttonClass({ size: "sm" })} disabled={!draft.from || !draft.to} onClick={() => apply(draft)}>
                    Apply
                  </PopoverClose>
                </div>
              )}
            </div>
          </div>
        </PopoverContent>
      </Popover>
      {/* The applied range, read once after it changes. */}
      <span className="sr-only" aria-live="polite">
        {said && `Selected ${said}.`}
      </span>
    </div>
  );
}

Files and dependencies

Adds
components/ui/date-range-picker.tsx
Packages
None
Brings along
ButtonCalendarDate inputPopoverChart foundationsSound engine
Icons
calendar-range

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor