Date Picker
SaveA button that opens the Calendar in a Popover, for a single date or a range, with presets such as Last 7 days.
- Category
- Data display
- Version
- 0.1.1
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Date Picker preview
Installation
npx @shakenui/cli add date-pickerReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add date-picker --dry-runUsage
date-picker-example.tsx
"use client";
import { DatePicker, rangeDatePresets, singleDatePresets } from "@/components/shaken/ui/date-picker";
export default function DatePickerExample() {
return (
<div className="flex flex-wrap items-end justify-center gap-6">
<div className="grid gap-1.5">
<label htmlFor="usage-range" className="text-sm font-medium text-zinc-950 dark:text-white">
Usage period
</label>
<DatePicker id="usage-range" mode="range" presets={rangeDatePresets} />
</div>
<div className="grid gap-1.5">
<label htmlFor="key-expiry" className="text-sm font-medium text-zinc-950 dark:text-white">
Key expires on
</label>
<DatePicker id="key-expiry" presets={singleDatePresets} minDate={new Date()} />
</div>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| mode | "single" | "range" | "single" | One date, or a range with a Done footer. |
| value / defaultValue / onValueChange | Date | null, or { from, to } | — | Selection, controlled or not. |
| presets | { label, value }[] | — | Quick picks beside the calendar. value can be a function of today. singleDatePresets and rangeDatePresets ship as defaults. |
| placeholder | string | — | Trigger text when nothing is picked. |
| numberOfMonths | 1 | 2 | 2 | Range mode on wide screens; narrow screens always show one month. |
| disabled / minDate / maxDate / weekStartsOn / locale | Calendar props | — | Passed to the Calendar. |
| id / aria-label / className / triggerDisabled | string / string / string / boolean | — | Trigger attributes. Pair id with a <label htmlFor>. |
| align | "start" | "center" | "end" | "start" | Popover alignment against the trigger. |
Accessibility
- The trigger is a Base UI Popover trigger (aria-expanded, aria-controls); its text is the picked date or the placeholder.
- Opening focuses the selected day (or today) in the grid, Escape closes, and focus returns to the trigger.
- Presets are toggle buttons with aria-pressed showing which one matches the current value.
- In range mode a polite live summary reads the span and day count ("Nov 8 to 14, 7 days"); Done stays disabled until an end date is picked.
- Dates are formatted with Intl.DateTimeFormat, including formatRange for ranges.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/date-picker.tsxdate-picker- Also installs calendar@0.1.0registry dependency
- Also installs popover@0.2.2registry dependency
- Also installs button@0.2.1registry dependency
- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/date-picker/0.1.1.json.
ui/date-picker.tsxShowHide
ui/date-picker.tsx
"use client";
import { useEffect, useMemo, useState } from "react";
import { Button } from "./button";
import { addDays, addMonths, Calendar, type CalendarProps, countDays, type DateRange, isSameDay, startOfDay } from "./calendar";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
export interface DatePreset<Value> {
label: string;
/** The value, or a function that computes it from today when the preset is picked. */
value: Value | ((today: Date) => Value);
}
/** Today, Tomorrow, and In a week. */
export const singleDatePresets: DatePreset<Date>[] = [
{ label: "Today", value: (today) => today },
{ label: "Tomorrow", value: (today) => addDays(today, 1) },
{ label: "In a week", value: (today) => addDays(today, 7) },
];
/** Today, Last 7 days, Last 30 days, This month, and Last month. */
export const rangeDatePresets: DatePreset<DateRange>[] = [
{ label: "Today", value: (today) => ({ from: today, to: today }) },
{ label: "Last 7 days", value: (today) => ({ from: addDays(today, -6), to: today }) },
{ label: "Last 30 days", value: (today) => ({ from: addDays(today, -29), to: today }) },
{ label: "This month", value: (today) => ({ from: new Date(today.getFullYear(), today.getMonth(), 1), to: today }) },
{
label: "Last month",
value: (today) => {
const start = addMonths(new Date(today.getFullYear(), today.getMonth(), 1), -1);
return { from: start, to: new Date(start.getFullYear(), start.getMonth() + 1, 0) };
},
},
];
function useWide() {
const [wide, setWide] = useState(true);
useEffect(() => {
const query = window.matchMedia("(min-width: 640px)");
const update = () => setWide(query.matches);
update();
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, []);
return wide;
}
type Shared = Pick<CalendarProps, "disabled" | "minDate" | "maxDate" | "weekStartsOn" | "locale"> & {
/** Text in the trigger when nothing is picked. */
placeholder?: string;
/** Turns the trigger off. */
triggerDisabled?: boolean;
/** Accessible name for the trigger when no visible label is next to it. */
"aria-label"?: string;
id?: string;
/** Classes for the trigger button. */
className?: string;
/** Popover alignment against the trigger. */
align?: "start" | "center" | "end";
};
export interface DatePickerSingleProps extends Shared {
mode?: "single";
value?: Date | null;
defaultValue?: Date | null;
onValueChange?: (value: Date | null) => void;
/** Quick picks beside the calendar. Pass `singleDatePresets` for the defaults. */
presets?: DatePreset<Date>[];
}
export interface DatePickerRangeProps extends Shared {
mode: "range";
value?: DateRange;
defaultValue?: DateRange;
onValueChange?: (value: DateRange) => void;
/** Quick picks beside the calendar. Pass `rangeDatePresets` for the defaults. */
presets?: DatePreset<DateRange>[];
/** Months shown on wide screens. Narrow screens always show one. */
numberOfMonths?: 1 | 2;
}
export type DatePickerProps = DatePickerSingleProps | DatePickerRangeProps;
function resolve<Value>(preset: DatePreset<Value>, today: Date): Value {
return typeof preset.value === "function" ? (preset.value as (today: Date) => Value)(today) : preset.value;
}
/**
* A button that opens a `Calendar` in a `Popover`, for one date or a range, with optional presets.
* A single date closes the popover when picked; a range stays open until Done, so either end can
* be adjusted.
*/
export function DatePicker(props: DatePickerProps) {
const {
mode = "single",
placeholder = mode === "range" ? "Pick a date range" : "Pick a date",
triggerDisabled,
disabled,
minDate,
maxDate,
weekStartsOn,
locale,
id,
className,
align = "start",
} = props;
const wide = useWide();
const [open, setOpen] = useState(false);
const [today, setToday] = useState(() => startOfDay(new Date()));
const [innerSingle, setInnerSingle] = useState<Date | null>(mode === "single" ? ((props as DatePickerSingleProps).defaultValue ?? null) : null);
const [innerRange, setInnerRange] = useState<DateRange>(
mode === "range" ? ((props as DatePickerRangeProps).defaultValue ?? { from: null, to: null }) : { from: null, to: null },
);
const single = mode === "single" ? ((props as DatePickerSingleProps).value !== undefined ? (props as DatePickerSingleProps).value ?? null : innerSingle) : null;
const range = mode === "range" ? ((props as DatePickerRangeProps).value ?? innerRange) : { from: null, to: null };
const [month, setMonth] = useState<Date>(() => (mode === "single" ? single : range.from) ?? today);
const dateFormat = useMemo(() => new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric" }), [locale]);
const summaryFormat = useMemo(() => new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" }), [locale]);
function setSingle(value: Date | null) {
const p = props as DatePickerSingleProps;
if (p.value === undefined) setInnerSingle(value);
p.onValueChange?.(value);
}
function setRange(value: DateRange) {
const p = props as DatePickerRangeProps;
if (p.value === undefined) setInnerRange(value);
p.onValueChange?.(value);
}
function onOpenChange(next: boolean) {
if (next) {
// Re-read the clock and show the month of the current value each time the picker opens.
const now = startOfDay(new Date());
setToday(now);
setMonth((mode === "single" ? single : range.from) ?? now);
}
setOpen(next);
}
let label: string | null = null;
if (mode === "single" && single) label = dateFormat.format(single);
if (mode === "range" && range.from) label = range.to ? dateFormat.formatRange(range.from, range.to) : `${dateFormat.format(range.from)} to …`;
const presets = (props.presets ?? []) as DatePreset<Date | DateRange>[];
const months = mode === "range" && wide ? ((props as DatePickerRangeProps).numberOfMonths ?? 2) : 1;
function isActive(preset: DatePreset<Date | DateRange>) {
const value = resolve(preset, today);
if (value instanceof Date) return isSameDay(value, single);
return isSameDay(value.from, range.from) && isSameDay(value.to, range.to);
}
function pick(preset: DatePreset<Date | DateRange>) {
const value = resolve(preset, today);
if (value instanceof Date) {
setSingle(value);
setOpen(false);
} else {
setRange(value);
// Show the end of the range; with two months, it lands in the right-hand one.
const end = value.to ?? value.from;
if (end) setMonth(months === 2 ? addMonths(end, -1) : end);
}
}
const calendarShared = { disabled, minDate, maxDate, weekStartsOn, locale, today, month, onMonthChange: setMonth, autoFocus: true };
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger
disabled={triggerDisabled}
id={id}
aria-label={props["aria-label"] ? `${props["aria-label"]}${label ? `, ${label}` : ""}` : undefined}
render={<Button variant="secondary" />}
className={cx(
"min-w-56 justify-start px-3 font-normal tabular-nums data-[popup-open]:border-zinc-950/20 dark:data-[popup-open]:border-white/25",
className,
)}
>
<CalendarGlyph />
<span className={cx("truncate", !label && "text-zinc-500")}>{label ?? placeholder}</span>
</PopoverTrigger>
<PopoverContent align={align} className="w-auto max-w-[calc(100vw-2rem)] p-0">
<div className={cx("flex", presets.length > 0 && "max-sm:flex-col")}>
{presets.length > 0 ? (
<div
role="group"
aria-label="Presets"
className={cx(
"flex gap-0.5 border-zinc-950/[0.07] p-2 dark:border-white/[0.08]",
// On narrow screens the row scrolls instead of widening the popover past the calendar.
"max-sm:w-0 max-sm:min-w-full max-sm:overflow-x-auto max-sm:border-b sm:w-36 sm:flex-col sm:border-r",
)}
>
{presets.map((preset) => {
const active = isActive(preset);
return (
<button
key={preset.label}
type="button"
aria-pressed={active}
onClick={() => pick(preset)}
className={cx(
"h-8 shrink-0 rounded-md px-2.5 text-left text-sm whitespace-nowrap",
"transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
active
? "bg-zinc-950/[0.06] font-medium text-zinc-950 dark:bg-white/[0.09] dark:text-white"
: "text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
)}
>
{preset.label}
</button>
);
})}
</div>
) : null}
<div className="grid">
<div className="p-3">
{mode === "single" ? (
<Calendar
{...calendarShared}
mode="single"
value={single}
onValueChange={(value) => {
setSingle(value);
setOpen(false);
}}
/>
) : (
<Calendar {...calendarShared} mode="range" value={range} onValueChange={setRange} numberOfMonths={months as 1 | 2} />
)}
</div>
{mode === "range" ? (
<div className="flex items-center gap-2 border-t border-zinc-950/[0.07] py-2.5 ps-4 pe-2.5 dark:border-white/[0.08]">
<p aria-live="polite" className="min-w-0 truncate text-xs text-zinc-500 tabular-nums">
{range.from && range.to
? `${summaryFormat.formatRange(range.from, range.to)}, ${countDays(range.from, range.to)} ${countDays(range.from, range.to) === 1 ? "day" : "days"}`
: range.from
? "Pick an end date"
: "Pick a start date"}
</p>
<Button variant="ghost" size="sm" className="ms-auto" disabled={!range.from} onClick={() => setRange({ from: null, to: null })}>
Clear
</Button>
<Button size="sm" disabled={!!range.from && !range.to} onClick={() => setOpen(false)}>
Done
</Button>
</div>
) : null}
</div>
</div>
</PopoverContent>
</Popover>
);
}
function CalendarGlyph() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="text-zinc-500">
<rect x="2.25" y="3.25" width="11.5" height="10.5" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M2.5 6.75h11M5.5 1.75v3M10.5 1.75v3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
);
}