Two Field Date Range Picker
Start and end date inputs joined in one frame that share a two month popover calendar. Use for report periods, leave requests and campaign dates where typing is as common as picking.
How it differs. Two typed fields over one calendar: the focused field decides which end a click sets, a dashed band previews it, a pick on the wrong side swaps the ends, and one message reports cross field errors.
Install
pnpm dlx shadcn@latest add @hazine/date-range-two-fieldsAdds 3 files, 2 shadcn primitives (calendar, popover), 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/date-range-two-fields.tsx, 426 lines
"use client"
import * as React from "react"
import { CalendarDays, CircleAlert, X } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Popover,
PopoverAnchor,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { useControllableState } from "@/hooks/use-controllable-state"
import { DateRangeTwoFieldsCalendar } from "./date-range-two-fields.calendar"
import {
DEFAULT_LABELS,
EMPTY,
ENDS,
createFormats,
daysIn,
findDay,
findErrors,
ordered,
parseTyped,
patternOf,
tabStops,
toDate,
withEnd,
type DateRange,
type DateRangeEnd,
type DateRangeTwoFieldsLabels,
type Draft,
} from "./date-range-two-fields.dates"
export { DEFAULT_LABELS }
export type { DateRange, DateRangeEnd, DateRangeTwoFieldsLabels }
const frameClass =
"flex overflow-hidden rounded-md border border-foreground/50 bg-background text-sm text-foreground transition-colors duration-100 has-[input:disabled]:pointer-events-none has-[input:disabled]:opacity-50 data-[invalid=true]:border-destructive"
const fieldClass =
"flex min-h-9 min-w-0 flex-1 cursor-text items-center gap-1 ps-3 transition-colors duration-100 has-[input:read-only]:bg-muted/50 data-[active=true]:bg-muted/50"
const inputClass =
"min-h-9 w-full min-w-0 flex-1 bg-transparent px-2 text-base tabular-nums placeholder:text-muted-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground aria-invalid:underline aria-invalid:decoration-destructive aria-invalid:decoration-wavy aria-invalid:underline-offset-4 md:text-sm"
const actionClass =
"flex size-9 shrink-0 touch-manipulation items-center justify-center text-muted-foreground transition-colors duration-100 hover:bg-muted/50 hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground active:bg-muted disabled:pointer-events-none disabled:opacity-50 aria-expanded:bg-muted/50 aria-expanded:text-foreground"
export interface DateRangeTwoFieldsProps extends Omit<
React.ComponentProps<"div">,
"defaultValue" | "onChange" | "role"
> {
/** A typed end may come before the start. The fields flag it, the value is not reordered. */
value?: DateRange
defaultValue?: DateRange
onValueChange?: (value: DateRange) => void
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
/** Earliest and latest day that can be chosen, as ISO dates. */
min?: string
max?: string
/** The day marked as today, as an ISO date. Defaults to the device date. */
today?: string
locale?: string
disabled?: boolean
readOnly?: boolean
/** A message from outside, such as a server check. Marks both fields invalid. */
error?: string
/** Names of two hidden inputs that submit the ISO dates with a form. */
startName?: string
endName?: string
labels?: Partial<DateRangeTwoFieldsLabels>
}
export function DateRangeTwoFields({
value: valueProp,
defaultValue,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
min,
max,
today,
locale = "en-US",
disabled = false,
readOnly = false,
error,
startName,
endName,
labels: labelsProp,
className,
...props
}: DateRangeTwoFieldsProps) {
const labels = { ...DEFAULT_LABELS, ...labelsProp }
const id = React.useId()
const errorId = `${id}-error`
const summaryId = `${id}-summary`
const frameRef = React.useRef<HTMLDivElement>(null)
const contentRef = React.useRef<HTMLDivElement>(null)
const startRef = React.useRef<HTMLInputElement>(null)
// False keeps focus in the field. Otherwise the grid takes it, on this day when it is shown.
const gridFocus = React.useRef<string | boolean>(false)
const [value, setValue] = useControllableState<DateRange>({
value: valueProp,
defaultValue: defaultValue ?? EMPTY,
onChange: onValueChange,
})
const [open, setOpen] = useControllableState({
value: openProp,
defaultValue: defaultOpen,
onChange: onOpenChange,
})
const [active, setActive] = React.useState<DateRangeEnd>("start")
const [drafts, setDrafts] = React.useState<
Record<DateRangeEnd, Draft | null>
>({ start: null, end: null })
const [hovered, setHovered] = React.useState<string | null>(null)
const [month, setMonth] = React.useState(() => {
const anchor = value.start ?? value.end ?? today
return anchor ? toDate(anchor) : undefined
})
const formats = React.useMemo(() => createFormats(locale), [locale])
const pattern = patternOf(formats, labels.pattern)
const locked = disabled || readOnly
const rejected = {
start: Boolean(drafts.start?.rejected && !value.start),
end: Boolean(drafts.end?.rejected && !value.end),
}
const { fields: fieldErrors, order: orderError, messages } = findErrors(
{ value, rejected, min, max, pattern, error },
formats,
labels
)
const cross = Boolean(error || orderError)
const blank = ENDS.every((end) => !value[end] && !drafts[end])
// A day that is already this end changes nothing, so it draws no band.
const previewRange =
hovered && hovered !== value[active]
? ordered({ ...value, [active]: hovered })
: null
const selected = ordered(value)
const days = messages.length === 0 ? daysIn(value) : 0
const guideDays = daysIn(previewRange ?? selected)
function focusDay() {
findDay(contentRef.current, gridFocus.current)?.focus()
}
function openCalendar(end: DateRangeEnd, toGrid: boolean, anchor?: string) {
if (locked) return
setActive(end)
gridFocus.current = toGrid && (anchor ?? value[end] ?? true)
if (open) {
// The grid is already mounted, so focus moves once this event has rendered.
if (toGrid) window.requestAnimationFrame(focusDay)
return
}
const shown = anchor ?? value[end] ?? value.start ?? value.end ?? today
setMonth(shown ? toDate(shown) : undefined)
setOpen(true)
}
function commitDraft(end: DateRangeEnd) {
const draft = drafts[end]
if (!draft || draft.rejected) return undefined
const text = draft.text.trim()
const iso = text === "" ? undefined : parseTyped(text, formats.order)
setDrafts((current) => ({
...current,
[end]: iso === null ? { text: draft.text, rejected: true } : null,
}))
setValue((current) => withEnd(current, end, iso ?? undefined))
if (iso) setMonth(toDate(iso))
return iso ?? undefined
}
function pickDay(iso: string) {
// The focused field decides which end this day sets. A pick that lands on
// the wrong side of the other end swaps the two.
const next = ordered({ ...value, [active]: iso })
setValue(next)
setDrafts((current) => ({ ...current, [active]: null }))
setHovered(null)
if (active === "end" && next.start && next.end) setOpen(false)
// A finished range starts over at the start the next time the calendar opens.
setActive(active === "start" ? "end" : "start")
}
function clear() {
setValue(EMPTY)
setDrafts({ start: null, end: null })
setHovered(null)
// The button disables itself once both fields are blank.
startRef.current?.focus()
}
function handleKeyDown(
event: React.KeyboardEvent<HTMLInputElement>,
end: DateRangeEnd
) {
if (event.key === "Enter") commitDraft(end)
if (event.key === "ArrowDown" && !locked) {
event.preventDefault()
openCalendar(end, true, commitDraft(end))
}
// While the calendar is open, Escape belongs to it.
if (event.key === "Escape" && drafts[end] && !open) {
setDrafts((current) => ({ ...current, [end]: null }))
}
}
const summary =
days > 0 && value.start && value.end ? (
<>
<span className="font-medium text-foreground tabular-nums">
{labels.days(days)}
</span>
{", "}
<time dateTime={value.start}>
{(value.start.slice(0, 4) === value.end.slice(0, 4)
? formats.short
: formats.long
).format(toDate(value.start))}
</time>{" "}
{labels.to}{" "}
<time dateTime={value.end}>{formats.long.format(toDate(value.end))}</time>
</>
) : locked ? null : (
labels.hint(pattern)
)
return (
<div
role="group"
data-slot="date-range-two-fields"
data-state={open ? "open" : "closed"}
className={cn("@container", className)}
{...props}
>
<Popover
open={open}
onOpenChange={(next) => {
if (next) openCalendar(active, true)
else setOpen(false)
}}
>
<PopoverAnchor asChild>
<div
ref={frameRef}
data-slot="date-range-two-fields-frame"
data-invalid={messages.length > 0 || undefined}
className={frameClass}
>
<div className="flex min-w-0 flex-1 flex-col @md:flex-row">
{ENDS.map((end) => {
const iso = value[end]
const typed = rejected[end] || !drafts[end]?.rejected
return (
<label
key={end}
htmlFor={`${id}-${end}`}
data-slot="date-range-two-fields-field"
data-active={(open && active === end) || undefined}
className={cn(
fieldClass,
end === "end" &&
"border-t border-border @md:border-s @md:border-t-0"
)}
>
<span className="min-w-9 shrink-0 text-muted-foreground">
{labels[end]}
</span>
<input
ref={end === "start" ? startRef : undefined}
id={`${id}-${end}`}
data-slot="date-range-two-fields-input"
type="text"
autoComplete="off"
spellCheck={false}
placeholder={pattern}
disabled={disabled}
readOnly={readOnly}
aria-invalid={
cross || Boolean(fieldErrors[end]) || undefined
}
aria-describedby={`${errorId} ${summaryId}`}
value={
(typed ? drafts[end]?.text : undefined) ??
(iso ? formats.field.format(toDate(iso)) : "")
}
onChange={(event) => {
const text = event.target.value
setDrafts((current) => ({
...current,
[end]: { text, rejected: false },
}))
}}
onFocus={() => setActive(end)}
onClick={() => openCalendar(end, false)}
onKeyDown={(event) => handleKeyDown(event, end)}
onBlur={() => commitDraft(end)}
className={inputClass}
/>
</label>
)
})}
</div>
<div className="flex shrink-0 flex-col border-s border-border @md:flex-row">
<button
type="button"
data-slot="date-range-two-fields-clear"
aria-label={labels.clear}
disabled={locked || blank}
onClick={clear}
className={actionClass}
>
<X aria-hidden="true" className="size-4" />
</button>
<PopoverTrigger asChild>
<button
type="button"
data-slot="date-range-two-fields-trigger"
aria-label={labels.calendar}
disabled={locked}
className={cn(
actionClass,
"border-t border-border @md:border-t-0"
)}
>
<CalendarDays aria-hidden="true" className="size-4" />
</button>
</PopoverTrigger>
</div>
</div>
</PopoverAnchor>
<PopoverContent
ref={contentRef}
align="start"
aria-label={labels.calendar}
className="max-h-(--radix-popover-content-available-height) w-auto overflow-y-auto"
onOpenAutoFocus={(event) => {
// Typing continues in the field unless the keyboard asked for the grid.
event.preventDefault()
if (gridFocus.current) focusDay()
}}
onCloseAutoFocus={(event) => {
const focused = document.activeElement
if (frameRef.current?.contains(focused)) event.preventDefault()
}}
onKeyDown={(event) => {
// The popover sits at the end of the page, so Tab off either edge
// would leave the document. It closes instead, and focus returns
// to the calendar button.
if (event.key !== "Tab") return
const stops = tabStops(event.currentTarget)
const edge = event.shiftKey ? stops[0] : stops[stops.length - 1]
if (event.target !== edge) return
event.preventDefault()
setOpen(false)
}}
onInteractOutside={(event) => {
// Moving between the two fields keeps the calendar open.
const target = event.target
if (target instanceof Node && frameRef.current?.contains(target)) {
event.preventDefault()
}
}}
>
<DateRangeTwoFieldsCalendar
selected={selected}
preview={previewRange}
month={month}
onMonthChange={setMonth}
min={min}
max={max}
today={today}
formats={formats}
labels={labels}
onDayPick={pickDay}
onDayPreview={setHovered}
/>
<div
data-slot="date-range-two-fields-guide"
className="flex items-baseline justify-between gap-4 border-t border-border px-2 pt-2"
>
<p aria-live="polite" className="font-medium">
<bdi>{active === "start" ? labels.pickStart : labels.pickEnd}</bdi>
</p>
{guideDays > 0 && (
<p className="text-muted-foreground tabular-nums">
<bdi>{labels.days(guideDays)}</bdi>
</p>
)}
</div>
</PopoverContent>
</Popover>
<div role="alert" id={errorId} data-slot="date-range-two-fields-error">
{messages.length > 0 && (
<p className="mt-1.5 flex items-start gap-1.5 text-sm text-destructive">
<CircleAlert aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
<bdi>{messages.join(" ")}</bdi>
</p>
)}
</div>
<div role="status" id={summaryId} data-slot="date-range-two-fields-summary">
{messages.length === 0 && summary && (
<p className="mt-1.5 text-sm text-muted-foreground">
{/* The labels may run the other way than the page, so they set their own direction. */}
<bdi>{summary}</bdi>
</p>
)}
</div>
{startName && (
<input type="hidden" name={startName} value={value.start ?? ""} disabled={disabled} />
)}
{endName && <input type="hidden" name={endName} value={value.end ?? ""} disabled={disabled} />}
</div>
)
}
components/hazine/date-range-two-fields.dates.ts, 241 lines
export type DateRangeEnd = "start" | "end"
/** Calendar days as ISO strings ("2026-11-16"), so no time zone is involved. */
export interface DateRange {
start?: string
end?: string
}
export interface DateRangeTwoFieldsLabels {
start: string
end: string
clear: string
calendar: string
pickStart: string
pickEnd: string
previousMonth: string
nextMonth: string
/** Added to a day's spoken name, as in "Today, Monday, November 16, 2026, selected". */
today: string
selected: string
/** The word between two dates in the summary. */
to: string
/** Placeholder letters for each part of the typed format. */
pattern: { day: string; month: string; year: string }
hint: (pattern: string) => string
days: (count: number) => string
invalidDate: (end: DateRangeEnd, pattern: string) => string
beforeMin: (end: DateRangeEnd, date: string) => string
afterMax: (end: DateRangeEnd, date: string) => string
endBeforeStart: string
}
const fieldName = (end: DateRangeEnd) =>
end === "start" ? "Start date" : "End date"
export const DEFAULT_LABELS: DateRangeTwoFieldsLabels = {
start: "Start",
end: "End",
clear: "Clear both dates",
calendar: "Choose dates in the calendar",
pickStart: "Pick a start date",
pickEnd: "Pick an end date",
previousMonth: "Previous month",
nextMonth: "Next month",
today: "Today",
selected: "selected",
to: "to",
pattern: { day: "DD", month: "MM", year: "YYYY" },
hint: (pattern) => `Type a date as ${pattern} or pick it in the calendar.`,
days: (count) => (count === 1 ? "1 day" : `${count} days`),
invalidDate: (end, pattern) =>
`${fieldName(end)} is not a date. Type it as ${pattern}.`,
beforeMin: (end, date) =>
`${fieldName(end)} is too early. Pick ${date} or later.`,
afterMax: (end, date) =>
`${fieldName(end)} is too late. Pick ${date} or earlier.`,
endBeforeStart:
"End date is before start date. Pick an end on or after the start.",
}
export const ENDS: DateRangeEnd[] = ["start", "end"]
export const EMPTY: DateRange = {}
const DAY_MS = 86_400_000
export type DatePart = keyof DateRangeTwoFieldsLabels["pattern"]
export interface Draft {
text: string
/** Committed text that did not parse. It stays visible so it can be fixed. */
rejected: boolean
}
export function toDate(iso: string) {
const [year = 0, month = 1, day = 1] = iso.split("-").map(Number)
return new Date(year, month - 1, day)
}
export function toIso(date: Date) {
const pad = (value: number, length: number) =>
String(value).padStart(length, "0")
return `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1, 2)}-${pad(date.getDate(), 2)}`
}
export function ordered(range: DateRange): DateRange {
return range.start && range.end && range.start > range.end
? { start: range.end, end: range.start }
: range
}
export function withEnd(range: DateRange, end: DateRangeEnd, iso: string | undefined) {
return range[end] === iso ? range : { ...range, [end]: iso }
}
export function daysIn(range: DateRange) {
if (!range.start || !range.end) return 0
const span = toDate(range.end).getTime() - toDate(range.start).getTime()
return Math.round(span / DAY_MS) + 1
}
type WeekStart = 0 | 1 | 2 | 3 | 4 | 5 | 6
/** First day of the week for the locale, 0 for Sunday. Undefined where the browser cannot tell. */
function weekStart(locale: string) {
const info = new Intl.Locale(locale) as Intl.Locale & {
getWeekInfo?: () => { firstDay: number }
weekInfo?: { firstDay: number }
}
const first = (info.getWeekInfo?.() ?? info.weekInfo)?.firstDay
return first === undefined ? undefined : ((first % 7) as WeekStart)
}
export function createFormats(locale: string) {
const numeric = { year: "numeric", month: "2-digit", day: "2-digit" } as const
const field = new Intl.DateTimeFormat(locale, numeric)
const isPart = (type: string): type is DatePart =>
type === "day" || type === "month" || type === "year"
const parts = field.formatToParts(new Date(2026, 0, 1))
return {
field,
parts: parts.map((part) => (isPart(part.type) ? part.type : part.value)),
order: parts.map((part) => part.type).filter(isPart),
long: new Intl.DateTimeFormat(locale, { dateStyle: "medium" }),
full: new Intl.DateTimeFormat(locale, { dateStyle: "full" }),
short: new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" }),
month: new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }),
weekday: new Intl.DateTimeFormat(locale, { weekday: "short" }),
weekdayLong: new Intl.DateTimeFormat(locale, { weekday: "long" }),
weekStartsOn: weekStart(locale),
}
}
export type Formats = ReturnType<typeof createFormats>
/** The typed format in placeholder letters, such as "MM/DD/YYYY". */
export function patternOf(
formats: Formats,
letters: DateRangeTwoFieldsLabels["pattern"]
) {
const isPart = (part: string): part is DatePart => part in letters
return formats.parts
.map((part) => (isPart(part) ? letters[part] : part))
.join("")
}
/** Names for the calendar's own controls, so they follow the locale and labels as well. */
export function calendarLabels(
formats: Formats,
labels: DateRangeTwoFieldsLabels
) {
return {
labelGrid: (date: Date) => formats.month.format(date),
labelWeekday: (date: Date) => formats.weekdayLong.format(date),
labelPrevious: () => labels.previousMonth,
labelNext: () => labels.nextMonth,
labelDayButton: (
date: Date,
modifiers: { today?: boolean; selected?: boolean }
) =>
[
modifiers.today && labels.today,
formats.full.format(date),
modifiers.selected && labels.selected,
]
.filter(Boolean)
.join(", "),
}
}
/** One message per field that is wrong on its own, and the order message when only the pair is. */
export function findErrors(
input: {
value: DateRange
rejected: Record<DateRangeEnd, boolean>
min?: string
max?: string
pattern: string
/** A message from outside. It leads the list. */
error?: string
},
formats: Formats,
labels: DateRangeTwoFieldsLabels
) {
const { value, min, max } = input
const check = (end: DateRangeEnd) => {
const iso = value[end]
if (input.rejected[end]) return labels.invalidDate(end, input.pattern)
if (iso && min && iso < min) {
return labels.beforeMin(end, formats.long.format(toDate(min)))
}
if (iso && max && iso > max) {
return labels.afterMax(end, formats.long.format(toDate(max)))
}
return null
}
const fields = { start: check("start"), end: check("end") }
const inverted = Boolean(value.start && value.end && value.start > value.end)
const order =
inverted && !fields.start && !fields.end ? labels.endBeforeStart : null
const messages = [input.error, fields.start, fields.end, order].filter(
(message): message is string => Boolean(message)
)
return { fields, order, messages }
}
/** Reads the locale order ("11/16/2026") or ISO ("2026-11-16"). Null when it is not a real day. */
export function parseTyped(text: string, order: DatePart[]) {
// Some locales close the date with a separator ("2026. 11. 16."), which leaves an empty chunk.
const chunks = text.split(/[\s./-]+/).filter(Boolean)
if (chunks.length !== 3 || chunks.some((chunk) => !/^\d{1,4}$/.test(chunk))) {
return null
}
const keys: DatePart[] =
chunks[0]?.length === 4 ? ["year", "month", "day"] : order
const read = (part: DatePart) => Number(chunks[keys.indexOf(part)])
const year = read("year") < 100 ? read("year") + 2000 : read("year")
const date = new Date(year, read("month") - 1, read("day"))
const real =
year >= 1000 &&
date.getMonth() === read("month") - 1 &&
date.getDate() === read("day")
return real ? toIso(date) : null
}
/** The button of one day when the grid shows it, otherwise the grid's own tab stop. */
export function findDay(content: HTMLElement | null, target: string | boolean) {
const day =
typeof target === "string"
? content?.querySelector<HTMLElement>(
`[data-day="${target}"]:not([data-outside]) button:not(:disabled)`
)
: null
return (
day ??
content?.querySelector<HTMLElement>('[role="grid"] button[tabindex="0"]')
)
}
export function tabStops(content: HTMLElement) {
return Array.from(content.querySelectorAll("button")).filter(
(button) => button.tabIndex === 0 && !button.disabled
)
}
components/hazine/date-range-two-fields.calendar.tsx, 107 lines
"use client"
import * as React from "react"
import { Calendar, CalendarDayButton } from "@/components/ui/calendar"
import {
calendarLabels,
toDate,
toIso,
type DateRange,
type DateRangeTwoFieldsLabels,
type Formats,
} from "./date-range-two-fields.dates"
// Dashed means provisional: the band the next click would commit. It sits above
// the day buttons, which are opaque inside the committed range.
const previewClass =
"before:pointer-events-none before:absolute before:inset-0 before:z-20 before:border-y before:border-dashed before:border-foreground/50"
const previewClassNames = {
preview: previewClass,
previewStart: "before:border-s",
previewEnd: "before:border-e",
}
function CalendarRoot({
rootRef,
...props
}: React.ComponentProps<"div"> & { rootRef?: React.Ref<HTMLDivElement> }) {
return <div data-slot="calendar" ref={rootRef} {...props} />
}
// The calendar primitive declares these two inline, which gives them a new
// identity on every render. A hovered day re-renders the calendar, so the grid
// would remount under the pointer and drop the click and the focus.
const stableComponents = { Root: CalendarRoot, DayButton: CalendarDayButton }
export interface DateRangeTwoFieldsCalendarProps {
/** The committed range, start before end. */
selected: DateRange
/** The range the next pick would commit, drawn as a dashed band. */
preview: DateRange | null
month: Date | undefined
onMonthChange: (month: Date) => void
min?: string
max?: string
today?: string
formats: Formats
labels: DateRangeTwoFieldsLabels
onDayPick: (iso: string) => void
/** Called with the hovered or focused day, and with null when the pointer or focus leaves it. */
onDayPreview: (iso: string | null) => void
}
export function DateRangeTwoFieldsCalendar({
selected,
preview,
month,
onMonthChange,
min,
max,
today,
formats,
labels,
onDayPick,
onDayPreview,
}: DateRangeTwoFieldsCalendarProps) {
const band =
preview?.start && preview.end
? { from: toDate(preview.start), to: toDate(preview.end) }
: undefined
return (
<Calendar
mode="range"
numberOfMonths={2}
showOutsideDays={false}
weekStartsOn={formats.weekStartsOn}
components={stableComponents}
labels={calendarLabels(formats, labels)}
formatters={{
formatCaption: (date) => formats.month.format(date),
formatWeekdayName: (date) => formats.weekday.format(date),
}}
selected={{
from: selected.start ? toDate(selected.start) : undefined,
to: selected.end ? toDate(selected.end) : undefined,
}}
onSelect={(_range, day) => onDayPick(toIso(day))}
month={month}
onMonthChange={onMonthChange}
today={today ? toDate(today) : undefined}
startMonth={min ? toDate(min) : undefined}
endMonth={max ? toDate(max) : undefined}
disabled={[
...(min ? [{ before: toDate(min) }] : []),
...(max ? [{ after: toDate(max) }] : []),
]}
modifiers={{ preview: band, previewStart: band?.from, previewEnd: band?.to }}
modifiersClassNames={previewClassNames}
onDayMouseEnter={(date) => onDayPreview(toIso(date))}
onDayMouseLeave={() => onDayPreview(null)}
onDayFocus={(date) => onDayPreview(toIso(date))}
onDayBlur={() => onDayPreview(null)}
/>
)
}
The demo in the preview, 155 lines
"use client"
import * as React from "react"
import {
DateRangeTwoFields,
type DateRange,
} from "@/components/hazine/date-range-two-fields"
const TODAY = "2026-11-11"
const DAILY_BUDGET = 180
const DAY_MS = 86_400_000
const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
})
function utcDay(iso: string) {
const [year = 0, month = 1, day = 1] = iso.split("-").map(Number)
return Date.UTC(year, month - 1, day)
}
function countDays({ start, end }: DateRange) {
if (!start || !end || start > end || start < TODAY) return 0
return Math.round((utcDay(end) - utcDay(start)) / DAY_MS) + 1
}
export default function DateRangeTwoFieldsDemo() {
const labelId = React.useId()
const [dates, setDates] = React.useState<DateRange>({
start: "2026-11-16",
end: "2026-11-29",
})
const days = countDays(dates)
return (
<div className="grid w-lg max-w-full gap-2">
<div id={labelId} className="text-sm font-medium">
Campaign dates
</div>
<DateRangeTwoFields
aria-labelledby={labelId}
value={dates}
onValueChange={setDates}
today={TODAY}
min={TODAY}
startName="starts_on"
endName="ends_on"
/>
<dl className="mt-2 divide-y divide-border border-t border-border text-sm">
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">Daily budget</dt>
<dd className="flex items-baseline gap-1 tabular-nums">
{money.format(DAILY_BUDGET)}
<span className="text-xs text-muted-foreground">/day</span>
</dd>
</div>
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">Days running</dt>
<dd className="tabular-nums">
{days > 0 ? days : <span className="text-muted-foreground">Not set</span>}
</dd>
</div>
<div className="flex items-baseline justify-between gap-4 py-2 font-semibold">
<dt>Campaign budget</dt>
<dd className="tabular-nums">{money.format(days * DAILY_BUDGET)}</dd>
</div>
</dl>
</div>
)
}
function Labelled({
label,
note,
narrow = false,
...props
}: React.ComponentProps<typeof DateRangeTwoFields> & {
label: string
note?: string
narrow?: boolean
}) {
const labelId = React.useId()
return (
<div className={narrow ? "grid w-xs max-w-full gap-2" : "grid w-lg max-w-full gap-2"}>
<div id={labelId} className="text-sm font-medium">
{label}
</div>
<DateRangeTwoFields aria-labelledby={labelId} today={TODAY} {...props} />
{note && <p className="text-xs text-muted-foreground">{note}</p>}
</div>
)
}
export const scenarios = {
empty: () => <Labelled label="Time off" min={TODAY} />,
invalid: () => (
<Labelled
label="Report period"
defaultValue={{ start: "2026-10-19", end: "2026-10-05" }}
max={TODAY}
/>
),
error: () => (
<Labelled
label="Time off"
defaultValue={{ start: "2026-12-21", end: "2026-12-30" }}
error="These dates overlap leave already approved for Dec 24 to Dec 28. Pick dates outside that week."
/>
),
disabled: () => (
<Labelled
label="Campaign dates"
defaultValue={{ start: "2026-10-05", end: "2026-10-25" }}
note="This campaign ended on Oct 25. Duplicate it to run it again with new dates."
disabled
/>
),
"read-only": () => (
<Labelled
label="Billing period"
defaultValue={{ start: "2026-11-01", end: "2026-11-30" }}
note="Set by your plan. The period renews on Dec 1."
readOnly
/>
),
bounded: () => (
<Labelled
label="Report period, fourth quarter"
defaultValue={{ start: "2026-10-01", end: "2026-11-10" }}
min="2026-10-01"
max="2026-12-31"
note="Orders are available from Oct 1 to Dec 31."
/>
),
overflow: () => (
<Labelled
narrow
label="Sabbatical, including the handover week before you leave"
defaultValue={{ start: "2026-12-28", end: "2027-06-30" }}
labels={{ start: "Last day", end: "Return" }}
max="2027-03-31"
/>
),
open: () => (
<Labelled
label="Report period"
defaultValue={{ start: "2026-10-26", end: "2026-11-08" }}
max={TODAY}
defaultOpen
/>
),
}
Props16
- value
- DateRange
- A typed end may come before the start. The fields flag it, the value is not reordered.
- defaultValue
- DateRange
- onValueChange
- (value: DateRange) => void
- open
- boolean
- defaultOpen
- boolean = false
- onOpenChange
- (open: boolean) => void
- min
- string
- Earliest and latest day that can be chosen, as ISO dates.
- max
- string
- today
- string
- The day marked as today, as an ISO date. Defaults to the device date.
- locale
- string = "en-US"
- disabled
- boolean = false
- readOnly
- boolean = false
- error
- string
- A message from outside, such as a server check. Marks both fields invalid.
- startName
- string
- Names of two hidden inputs that submit the ISO dates with a form.
- endName
- string
- labels
- Partial<DateRangeTwoFieldsLabels>
- Overrides for every string the component renders or speaks: field names, button names, the calendar's month buttons and day names, the hint, the day count and the four error messages.
Also accepts every prop of Omit< React.ComponentProps<"div">, "defaultValue" | "onChange" | "role" >.
Accessibility
- Pattern
- Form with labelled fields, Grid (APG, opens in a new tab)
- Keyboard
Keyboard support for Two Field Date Range Picker Key Effect Tab Moves through start field, end field, clear button and calendar button Arrow Down in a field Commits typed text, opens the calendar and moves focus to that field's date in the grid, or to today when the field is empty. That field is the end the next pick sets Enter in a field Commits typed text, then submits the form as usual Escape Closes the calendar. From the grid, focus returns to the calendar button. With the calendar closed, discards typed text that is not committed Enter or Space on the calendar button Opens the calendar and moves focus to the grid, or closes it Tab in the calendar Moves through previous month, next month and the day grid. Past either end, closes the calendar and returns focus to the calendar button Arrow keys in the grid Move by day or week and preview the range Home, End Move to the start or end of the week Page Up, Page Down Move by month, or by year with Shift Enter or Space on a day Sets the active end, swapping the two when the day lands on the wrong side of the other end. A start pick moves on to the end, an end pick that completes the range closes the calendar and returns focus to the calendar button Enter or Space on Clear Empties both fields and moves focus to the start field - Screen reader
A group holding two labelled text inputs, a clear button and a calendar button. The calendar is a non-modal dialog with two date grids that mark the range through aria-selected, and it announces which end the next pick sets. Errors sit in an alert region and the day count in a status region, both described on each input. Day, month and weekday names follow the locale.
- Announces: {count} days, {start} to {end}
- Announces: Pick a start date
- Announces: Pick an end date
- Announces: Start date is not a date. Type it as {pattern}.
- Announces: End date is too late. Pick {date} or earlier.
- Announces: End date is before start date. Pick an end on or after the start.
- Reduced motion
- No motion of its own. Colour transitions only. The popover primitive keeps the host's open and close animation.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies4
- calendar
- popover
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.