DatePicker & DateRangePicker
Popover calendar for single dates and ranges, with presets and month navigation.
import { DatePicker, MonthGrid, DateRangePicker }from "@/components/ui"
Specification
Selects a single date from a popover calendar with month/year navigation; DateRangePicker selects a start/end range with presets.
Props (7)
Every prop this component accepts, its type, default, and how to use it.
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | — | Explicit element id, wired to the label (DatePicker). |
| label | string | — | Visible field label shown above the trigger. |
| hint | string | — | Helper text shown below the field. |
| value* | Date | null | — | Controlled selected date (DatePicker); null when unset. |
| onChange* | (d: Date | null) => void | — | Called with the chosen date, or null when cleared (DatePicker). |
| min | Date | — | Earliest selectable date; earlier days are disabled. |
| max | Date | — | Latest selectable date; later days are disabled. |
Single date & range
Full source
The complete component, read from
src/components/ui/calendar.tsx.calendar.tsx
"use client";
import { useState, useRef, useEffect, useCallback, type KeyboardEvent as ReactKeyboardEvent } from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, ChevronRight, ChevronDown, Calendar as CalIcon, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { usePopoverPosition, useMounted } from "@/hooks";
import { Field, controlBase, controlClasses } from "./field";
const DOW = ["M", "T", "W", "T", "F", "S", "S"];
const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const sameDay = (a: Date | null, b: Date | null) => a && b && a.toDateString() === b.toDateString();
const fmt = (d: Date | null) => d ? d.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }) : "";
function monthCells(y: number, m: number): (Date | null)[] {
const start = (new Date(y, m, 1).getDay() + 6) % 7;
const days = new Date(y, m + 1, 0).getDate();
const cells: (Date | null)[] = Array(start).fill(null);
for (let d = 1; d <= days; d++) cells.push(new Date(y, m, d));
while (cells.length % 7) cells.push(null);
return cells;
}
function yearRange(viewYear: number, min?: Date, max?: Date): number[] {
const start = min ? min.getFullYear() : viewYear - 100;
const end = max ? max.getFullYear() : viewYear + 10;
const lo = Math.min(start, viewYear);
const hi = Math.max(end, viewYear);
const years: number[] = [];
for (let y = lo; y <= hi; y++) years.push(y);
return years;
}
interface MiniSelectOption {
value: number;
label: string;
}
function MiniSelect({
value,
options,
ariaLabel,
onChange,
container,
}: {
value: number;
options: readonly MiniSelectOption[];
ariaLabel: string;
onChange: (value: number) => void;
container: HTMLElement | null;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [highlighted, setHighlighted] = useState(-1);
const triggerRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const initialScrollDone = useRef(false);
const filteredOptions = query
? options.filter((o) => o.label.toLowerCase().includes(query.toLowerCase()))
: options;
useEffect(() => {
if (!open) {
initialScrollDone.current = false;
return;
}
const h = (e: globalThis.MouseEvent) => {
const target = e.target as Node;
if (!triggerRef.current?.contains(target) && !listRef.current?.contains(target)) {
setOpen(false);
setQuery("");
}
};
document.addEventListener("mousedown", h);
return () => document.removeEventListener("mousedown", h);
}, [open]);
useEffect(() => {
if (open && !initialScrollDone.current) {
inputRef.current?.focus();
const idx = filteredOptions.findIndex((o) => o.value === value);
setHighlighted(idx >= 0 ? idx : 0);
requestAnimationFrame(() => {
const selected = listRef.current?.querySelector<HTMLElement>('[data-selected="true"]');
selected?.scrollIntoView({ block: "center" });
initialScrollDone.current = true;
});
}
}, [open, value, filteredOptions]);
useEffect(() => {
if (highlighted >= 0 && initialScrollDone.current) {
const el = listRef.current?.querySelector<HTMLElement>(`[data-index="${highlighted}"]`);
el?.scrollIntoView({ block: "nearest" });
}
}, [highlighted]);
const close = useCallback(() => {
setOpen(false);
setQuery("");
setHighlighted(-1);
}, []);
const select = useCallback((opt: MiniSelectOption) => {
onChange(opt.value);
close();
}, [onChange, close]);
const onKeyDown = (e: ReactKeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setHighlighted((i) => Math.min(i + 1, filteredOptions.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setHighlighted((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter" && filteredOptions[highlighted]) {
e.preventDefault();
select(filteredOptions[highlighted]);
} else if (e.key === "Escape") {
close();
}
};
const selected = options.find((o) => o.value === value);
return (
<div className="relative">
<button
ref={triggerRef}
type="button"
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
onClick={() => setOpen((o) => !o)}
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-sm font-medium tabular-nums text-text hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
{selected?.label ?? value}
<ChevronDown size={13} className="text-text-tertiary" aria-hidden />
</button>
{open && (
<div
ref={listRef}
data-calendar-mini-select=""
className="absolute left-0 top-full z-50 mt-1 w-36 overflow-hidden rounded-lg border border-border bg-surface shadow-lg"
>
<div className="border-b border-border p-1.5">
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setHighlighted(0);
}}
onKeyDown={onKeyDown}
placeholder="Type to filter…"
className="w-full rounded bg-bg-secondary px-2 py-1 text-sm text-text outline-none placeholder:text-text-tertiary"
/>
</div>
<ul
role="listbox"
aria-label={ariaLabel}
className="max-h-48 overflow-auto p-1"
>
{filteredOptions.length === 0 ? (
<li className="px-2 py-1.5 text-sm text-text-tertiary">No match</li>
) : (
filteredOptions.map((option, idx) => {
const isSelected = option.value === value;
const isHighlighted = idx === highlighted;
return (
<li key={option.value}>
<button
type="button"
role="option"
aria-selected={isSelected}
data-selected={isSelected}
data-index={idx}
onMouseEnter={() => setHighlighted(idx)}
onClick={() => select(option)}
className={cn(
"w-full rounded px-2 py-1 text-left text-sm tabular-nums text-text focus-visible:outline-none",
isHighlighted && "bg-bg-hover",
isSelected && "font-semibold text-accent"
)}
>
{option.label}
</button>
</li>
);
})
)}
</ul>
</div>
)}
</div>
);
}
interface MonthGridProps {
y: number;
m: number;
selected?: Date | null;
rangeStart?: Date | null;
rangeEnd?: Date | null;
hover?: Date | null;
onPick: (d: Date) => void;
onHover?: (d: Date) => void;
min?: Date;
max?: Date;
}
export function MonthGrid({ y, m, selected, rangeStart, rangeEnd, hover, onPick, onHover, min, max }: MonthGridProps) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const inRange = (d: Date | null) => {
const end = rangeEnd || hover;
if (!rangeStart || !end || !d) return false;
const [a, b] = rangeStart <= end ? [rangeStart, end] : [end, rangeStart];
return d > a && d < b;
};
return (
<div className="w-60">
<div className="mb-2 grid grid-cols-7">
{DOW.map((d, i) => <span key={i} className="text-center text-xs font-medium text-text-tertiary">{d}</span>)}
</div>
<div className="grid grid-cols-7 gap-y-1">
{monthCells(y, m).map((d, i) => {
if (!d) return <span key={i} />;
const off = (min ? d < min : false) || (max ? d > max : false);
const isStart = sameDay(d, rangeStart ?? null);
const isEnd = sameDay(d, rangeEnd ?? null);
const on = sameDay(d, selected ?? null) || isStart || isEnd;
const mid = inRange(d);
const isToday = sameDay(d, today);
return (
<button
key={i} disabled={off}
onClick={() => onPick(d)}
onMouseEnter={() => onHover?.(d)}
className={cn(
"relative mx-auto flex h-7 w-7 items-center justify-center text-sm tabular-nums transition-colors",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed",
on ? "bg-accent text-on-accent font-semibold" : mid ? "bg-accent-light text-text" : "text-text",
isToday && !on && "ring-1 ring-inset ring-accent",
off && "opacity-40 text-text-tertiary"
)}
style={{ borderRadius: mid ? 0 : 6 }}
>
{d.getDate()}
</button>
);
})}
</div>
</div>
);
}
interface DatePickerProps {
id?: string;
label?: string;
hint?: string;
value: Date | null;
onChange: (d: Date | null) => void;
min?: Date;
max?: Date;
}
export function DatePicker({ id, label, hint, value, onChange, min, max }: DatePickerProps) {
const [open, setOpen] = useState(false);
const [cur, setCur] = useState(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const anchorRef = useRef<HTMLButtonElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const position = usePopoverPosition(anchorRef, open, { minWidth: 260, preferredHeight: 340 });
const mounted = useMounted();
const [portalTarget, setPortalTarget] = useState<HTMLElement | null>(null);
const toggleOpen = () => {
setOpen((prev) => {
const next = !prev;
setPortalTarget(
next ? (anchorRef.current?.closest<HTMLElement>('[role="dialog"]') ?? document.body) : null
);
return next;
});
};
useEffect(() => {
const h = (e: globalThis.MouseEvent) => {
const target = e.target as Element;
if (
!anchorRef.current?.contains(target) &&
!panelRef.current?.contains(target) &&
!target.closest?.("[data-calendar-mini-select]")
) {
setOpen(false);
setPortalTarget(null);
}
};
document.addEventListener("mousedown", h);
return () => document.removeEventListener("mousedown", h);
}, []);
const shift = (n: number) => setCur(new Date(cur.getFullYear(), cur.getMonth() + n, 1));
const setMonth = (mm: number) => setCur(new Date(cur.getFullYear(), mm, 1));
const setYear = (yr: number) => setCur(new Date(yr, cur.getMonth(), 1));
const years = yearRange(cur.getFullYear(), min, max);
return (
<Field label={label} hint={hint} htmlFor={id}>
<div className="relative flex items-center">
<button ref={anchorRef} id={id} onClick={toggleOpen} className={cn(controlBase, controlClasses(), "flex h-10 items-center gap-2 px-3 text-left", value ? "pr-8" : "")}>
<CalIcon size={15} className="text-text-tertiary" aria-hidden />
<span className={cn("tabular-nums", value ? "text-text" : "text-text-tertiary")}>{value ? fmt(value) : "Select a date"}</span>
</button>
{value && (
<button
type="button"
onClick={(e) => { e.stopPropagation(); onChange(null); }}
aria-label="Clear date"
className="absolute right-2 rounded p-0.5 text-text-tertiary hover:opacity-70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<X size={14} aria-hidden />
</button>
)}
</div>
{open && position && mounted && portalTarget && createPortal(
<div ref={panelRef} className="pointer-events-auto z-50 overflow-visible rounded-lg border border-border bg-surface p-3 shadow-lg" style={position.style}>
<div className="mb-3 flex items-center justify-between">
<button type="button" onClick={() => shift(-1)} className="rounded p-1 text-text-secondary hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent" aria-label="Previous month"><ChevronLeft size={16} aria-hidden /></button>
<span className="flex items-center gap-1">
<MiniSelect
ariaLabel="Month"
value={cur.getMonth()}
onChange={setMonth}
options={MONTHS.map((name, i) => ({ value: i, label: name }))}
container={portalTarget}
/>
<MiniSelect
ariaLabel="Year"
value={cur.getFullYear()}
onChange={setYear}
options={years.map((yr) => ({ value: yr, label: String(yr) }))}
container={portalTarget}
/>
</span>
<button type="button" onClick={() => shift(1)} className="rounded p-1 text-text-secondary hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent" aria-label="Next month"><ChevronRight size={16} aria-hidden /></button>
</div>
<MonthGrid y={cur.getFullYear()} m={cur.getMonth()} selected={value} min={min} max={max} onPick={(d) => { onChange(d); setOpen(false); setPortalTarget(null); }} />
</div>,
portalTarget
)}
</Field>
);
}Dependencies
To use DatePicker & DateRangePicker you also need the following. Copy these into your project alongside it.
Recommended folder structure
project structure
src/components/ui/ ├─ calendar.tsx └─ field.tsx src/hooks/ ├─ use-mounted.ts └─ use-popover-position.ts src/lib/ └─ utils.ts
Dependency files
These supporting files aren’t components — copy each one into the matching path above.
src/components/ui/field.tsx
field.tsx
"use client";
import { type ReactNode } from "react";
import { cn } from "@/lib/utils";
interface FieldCounter {
text: string;
warn?: boolean;
}
interface FieldProps {
label?: string;
hint?: string;
error?: string;
required?: boolean;
htmlFor?: string;
counter?: FieldCounter;
messageId?: string;
children: ReactNode;
}
export function Field({
label,
hint,
error,
required,
htmlFor,
counter,
messageId,
children,
}: FieldProps) {
const message = error || hint;
return (
<div className="flex w-full flex-col gap-1.5">
{label && (
<label
htmlFor={htmlFor}
className="flex items-center gap-1 text-[13px] font-medium text-text"
>
{label}
{required && (
<span className="text-error" aria-hidden>
*
</span>
)}
</label>
)}
{children}
<div className="flex items-start justify-between gap-3">
<p
id={messageId}
className={cn("text-xs leading-snug", error ? "text-error" : "text-text-secondary")}
>
{message || "\u00A0"}
</p>
{counter && (
<span
className={cn(
"shrink-0 text-xs tabular-nums",
counter.warn ? "text-error" : "text-text-tertiary"
)}
>
{counter.text}
</span>
)}
</div>
</div>
);
}
export const controlBase = cn(
"w-full rounded-lg border text-sm bg-surface text-text transition-colors",
"placeholder:text-text-tertiary",
"focus:outline-none focus-visible:outline-none focus-visible:border-accent",
"disabled:cursor-not-allowed disabled:bg-bg-secondary disabled:opacity-60",
"read-only:bg-bg-secondary"
);
export function controlClasses(error?: string, disabled?: boolean, readOnly?: boolean) {
return cn(
error ? "border-error focus-visible:border-error" : "border-border",
readOnly && "read-only:bg-bg-secondary",
disabled && "text-text-tertiary"
);
}src/hooks/use-mounted.ts
use-mounted.ts
"use client";
import { useState, useEffect } from "react";
/**
* Returns true once the component has mounted on the client.
* Useful for portals and anything that needs `document` to exist.
*/
export function useMounted(): boolean {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
return mounted;
}src/hooks/use-popover-position.ts
use-popover-position.ts
"use client";
import { useState, useEffect, useCallback, type RefObject, type CSSProperties } from "react";
interface PopoverPositionOptions {
align?: "start" | "center" | "end";
gap?: number;
viewportPadding?: number;
preferredHeight?: number;
matchWidth?: boolean;
minWidth?: number;
}
interface PopoverPosition {
placement: "top" | "bottom";
style: CSSProperties;
}
/**
* Compute a fixed-position popover style anchored to a ref element.
* Opens downward by default; flips upward when there isn't room below
* AND there's more room above. Clamps horizontally so nothing renders
* past the viewport edge. Re-measures on scroll/resize while open.
*/
export function usePopoverPosition(
anchorRef: RefObject<HTMLElement | null>,
open: boolean,
options: PopoverPositionOptions = {}
): PopoverPosition | null {
const {
align = "start",
gap = 4,
viewportPadding = 8,
preferredHeight = 320,
matchWidth = false,
minWidth,
} = options;
const [position, setPosition] = useState<PopoverPosition | null>(null);
const measure = useCallback(() => {
const anchor = anchorRef.current;
if (!anchor) return;
const rect = anchor.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const spaceBelow = vh - rect.bottom - viewportPadding;
const spaceAbove = rect.top - viewportPadding;
const placement =
spaceBelow < Math.min(preferredHeight, 160) && spaceAbove > spaceBelow
? "top"
: "bottom";
const maxHeight = Math.max(
120,
Math.min(preferredHeight, placement === "top" ? spaceAbove : spaceBelow)
);
const width = matchWidth ? rect.width : minWidth;
let left = align === "end" && width ? rect.right - width : rect.left;
if (align === "center" && width)
left = rect.left + rect.width / 2 - width / 2;
left = width
? Math.min(Math.max(left, viewportPadding), vw - width - viewportPadding)
: Math.min(Math.max(left, viewportPadding), vw - viewportPadding);
setPosition({
placement,
style: {
position: "fixed",
top: placement === "top" ? undefined : rect.bottom + gap,
bottom: placement === "top" ? vh - rect.top + gap : undefined,
left,
width: matchWidth ? rect.width : undefined,
minWidth: !matchWidth ? minWidth : undefined,
maxHeight,
},
});
}, [anchorRef, align, gap, viewportPadding, preferredHeight, matchWidth, minWidth]);
useEffect(() => {
if (!open) {
setPosition(null);
return;
}
measure();
window.addEventListener("scroll", measure, true);
window.addEventListener("resize", measure);
return () => {
window.removeEventListener("scroll", measure, true);
window.removeEventListener("resize", measure);
};
}, [open, measure]);
return position;
}src/lib/utils.ts
utils.ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class names with clsx semantics + Tailwind conflict resolution.
* Prefer this in all components.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
/**
* Concatenate class names, filtering out falsy values.
* @deprecated Prefer {@link cn} — it also resolves Tailwind class conflicts.
*/
export function cx(...args: (string | false | null | undefined)[]): string {
return args.filter(Boolean).join(" ");
}
/**
* Focus ring style helper.
* @deprecated Focus rings are now handled globally via the
* `:focus-visible` rule in `globals.css` and the `focus-visible:*`
* utilities. This remains only for backwards compatibility.
*/
export function ring(color: string = "var(--color-accent)") {
return { outlineColor: color };
}