Date Range Picker Card
Date range picker card for booking and reporting filters: a labeled trigger opens a range calendar with typed start and end fields in a popover, preset to a 20-day span built with date-fns.
"use client"
import { addDays } from "date-fns"
import { DateRangePicker } from "@/components/controls/date-range-picker"
import { Card, CardContent } from "@/components/ui/card"
// The copy: change text here, not in the markup.
const COPY = {
label: "Pick a date",
placeholder: "Pick a date",
} as const
// A fixed sample date, made in this client file so the server and the
// browser both read it as the same day, whatever their time zones.
const START = new Date(2026, 0, 20)
/**
* A date range field in a card: a label and a button showing the chosen
* range, which opens a calendar with typed start and end dates. It starts
* with January 20 to February 9, 2026 selected.
*
* The label and placeholder live in `COPY`; the start date is `START`.
*/
export default function DateRangePickerCard({
defaultOpen = false,
}: {
/** Opens the calendar on first render. Defaults to `false`. */
defaultOpen?: boolean
}) {
return (
<Card className="mx-auto w-full max-w-md">
<CardContent>
<DateRangePicker
label={COPY.label}
placeholder={COPY.placeholder}
defaultValue={{ from: START, to: addDays(START, 20) }}
defaultOpen={defaultOpen}
/>
</CardContent>
</Card>
)
}
"use client"
import { useId, useState, type ComponentProps, type ReactNode } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { CalendarBlankIcon } from "@phosphor-icons/react"
import { cn } from "cn"
import { format, isValid, parse } from "date-fns"
import { type DateRange } from "react-day-picker"
import { Controller, useForm, useWatch } from "react-hook-form"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Kbd } from "@/components/ui/kbd"
import {
Popover,
PopoverContent,
PopoverTitle,
PopoverTrigger,
} from "@/components/ui/popover"
type DateRangePickerProps = Omit<
ComponentProps<typeof Field>,
"children" | "defaultValue"
> & {
/** The field's label, tied to the button that opens the calendar. It also names the popup. */
label: ReactNode
/** The button's text before any range is applied. */
placeholder: ReactNode
/** Controlled with value + onValueChange, or seeded with defaultValue. */
value?: DateRange
/**
* The range applied at first, when the picker keeps the value itself.
* Make the dates in a client file: a Date passed down from a Server
* Component arrives as a fixed instant, and can read as the day before
* or after in the reader's time zone.
*/
defaultValue?: DateRange
/** Called with the range each time one is applied, and with `undefined` when it is cleared. */
onValueChange?: (range: DateRange | undefined) => void
/**
* date-fns pattern for the button's text. By default the date, and with
* `time` the date and the time.
*/
dateFormat?: string
/** How many months the calendar shows side by side; 1 by default. */
numberOfMonths?: number
/**
* Adds a start and an end time field, read in the reader's own time zone.
* Off by default: the range is then two days, each at midnight.
*/
time?: boolean
/** Opens the calendar on first render. */
defaultOpen?: boolean
}
// What the fields hold while a range is being chosen: text, as typed.
type Draft = {
startDate: string
startTime: string
endDate: string
endTime: string
}
// How the fields write a value, and the other forms they accept when typed.
const DATE_TEXT = "MMM dd, yyyy"
const TIME_TEXT = "hh:mm a"
const DATE_FORMATS = [
"MMM d, yyyy",
"MMM d yyyy",
"MMMM d, yyyy",
"M/d/yyyy",
"yyyy-MM-dd",
]
const TIME_FORMATS = ["h:mm a", "h:mma", "h a", "ha", "H:mm"]
// The picker's own words: change or translate them here.
const COPY = {
start: "Start",
end: "End",
startTime: "Start time",
endTime: "End time",
datePlaceholder: "Jan 05, 2026",
timePlaceholder: "1:00 PM",
clear: "Clear",
apply: "Apply",
errors: {
date: "Enter a date like Jan 5, 2026.",
time: "Enter a time like 1:00 PM.",
gap: "That time does not exist on this day.",
order: "The end is before the start.",
},
} as const
// A fixed day with no clock change, for reading a time by itself.
const PLAIN_DAY = new Date(2001, 0, 1)
/**
* The day a typed date names, at midnight; `undefined` when it is not a
* date. Only a four-digit year is taken: a year still being typed
* ("Jan 5, 2") and one with a digit too many ("Jan 5, 20266") both read as
* real years otherwise.
*/
function readDate(text: string) {
for (const pattern of DATE_FORMATS) {
const date = parse(text.trim(), pattern, PLAIN_DAY)
const year = date.getFullYear()
if (isValid(date) && year >= 1000 && year <= 9999) return date
}
return undefined
}
/** The hour and minute a typed time names; `undefined` when it is not a time. */
function readTime(text: string) {
for (const pattern of TIME_FORMATS) {
const date = parse(text.trim(), pattern, PLAIN_DAY)
if (isValid(date))
return { hours: date.getHours(), minutes: date.getMinutes() }
}
return undefined
}
/**
* A day at a time of day, in the reader's own zone; `undefined` when the
* clock skips that time on that day, as it does when daylight saving
* starts. When the clock repeats an hour, this is its first occurrence.
*/
function at(day: Date, clock: { hours: number; minutes: number }) {
const date = new Date(
day.getFullYear(),
day.getMonth(),
day.getDate(),
clock.hours,
clock.minutes
)
return date.getHours() === clock.hours && date.getMinutes() === clock.minutes
? date
: undefined
}
type Problem = { field: keyof Draft; message: string }
/**
* Reads the four fields into a range, or into the list of what is wrong
* with them. The schema and Apply both use it, so what validates is exactly
* what is applied.
*/
function readDraft(draft: Draft, time: boolean) {
const problems: Problem[] = []
const startDay = readDate(draft.startDate)
const endDay = readDate(draft.endDate)
if (!startDay)
problems.push({ field: "startDate", message: COPY.errors.date })
if (!endDay) problems.push({ field: "endDate", message: COPY.errors.date })
let from = startDay
let to = endDay
if (time) {
const startClock = readTime(draft.startTime)
const endClock = readTime(draft.endTime)
if (!startClock)
problems.push({ field: "startTime", message: COPY.errors.time })
if (!endClock)
problems.push({ field: "endTime", message: COPY.errors.time })
if (startDay && startClock) {
from = at(startDay, startClock)
if (!from) problems.push({ field: "startTime", message: COPY.errors.gap })
}
if (endDay && endClock) {
to = at(endDay, endClock)
if (!to) problems.push({ field: "endTime", message: COPY.errors.gap })
}
}
if (from && to && to < from)
problems.push({ field: "endDate", message: COPY.errors.order })
return problems.length || !from || !to
? { problems, range: undefined }
: { problems, range: { from, to } satisfies DateRange }
}
/** The fields' text for an applied range; empty when there is none. */
function toDraft(range: DateRange | undefined, time: boolean): Draft {
return {
startDate: range?.from ? format(range.from, DATE_TEXT) : "",
startTime: range?.from && time ? format(range.from, TIME_TEXT) : "",
endDate: range?.to ? format(range.to, DATE_TEXT) : "",
endTime: range?.to && time ? format(range.to, TIME_TEXT) : "",
}
}
/** The form's schema: every problem `readDraft` finds, on its own field. */
const draftSchema = (time: boolean) =>
z
.object({
startDate: z.string(),
startTime: z.string(),
endDate: z.string(),
endTime: z.string(),
})
.superRefine((draft, context) => {
for (const problem of readDraft(draft, time).problems) {
context.addIssue({
code: "custom",
path: [problem.field],
message: problem.message,
})
}
})
/**
* A labelled button that opens a date range picker in a popover and shows
* the applied range. Pick two days in the calendar, or type the start and
* end dates in the fields under it. Nothing changes until Apply, which
* Enter also triggers; a field that cannot be read says so and blocks
* Apply. Clear empties the range.
*
* With `time`, each end also has a time field, read in the reader's own
* time zone; without it the range is two days at midnight. With one month
* the popover is 280px wide, or as wide as the screen allows, and the
* calendar and the fields share that width. The picker's own words
* (Start, End, Clear, Apply and the error messages) live in `COPY`. Other
* props go to the Field.
*/
function DateRangePicker(pickerProps: DateRangePickerProps) {
const {
label,
placeholder,
value,
defaultValue,
onValueChange,
numberOfMonths = 1,
time = false,
dateFormat = time ? "LLL dd, y h:mm a" : "LLL dd, y",
defaultOpen = false,
className,
...props
} = pickerProps
const id = useId()
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const controlled = Object.hasOwn(pickerProps, "value")
const range = controlled ? value : uncontrolled
const [open, setOpen] = useState(defaultOpen)
const [month, setMonth] = useState(range?.from ?? new Date())
const form = useForm<Draft>({
resolver: zodResolver(draftSchema(time)),
defaultValues: toDraft(range, time),
})
const draft = useWatch({ control: form.control })
// The days the calendar marks: whatever the two date fields read as now.
const shownFrom = readDate(draft.startDate ?? "")
const typedTo = readDate(draft.endDate ?? "")
// An end typed before the start is not drawn: the calendar would take its
// next pick from a range that runs backwards.
const shownTo =
shownFrom && typedTo && typedTo >= shownFrom ? typedTo : undefined
const anyText = Object.values(draft).some(Boolean)
// A time field's error counts only while the time fields are shown.
const { errors } = form.formState
const startErrors = [errors.startDate, time ? errors.startTime : undefined]
const endErrors = [errors.endDate, time ? errors.endTime : undefined]
const startWrong = startErrors.some(Boolean)
const endWrong = endErrors.some(Boolean)
// Once Apply has been tried, every change checks all four fields again:
// fixing the start also settles "the end is before the start".
function recheck() {
if (form.formState.isSubmitted) void form.trigger()
}
function write(field: keyof Draft, text: string) {
form.setValue(field, text, { shouldDirty: true })
}
// The calendar writes the days it is given into the two date fields. With
// `time`, an empty time field gets the start or the end of the day, once
// its own date is picked: a time with no date would look half-filled.
function pickDays(next: DateRange | undefined) {
write("startDate", next?.from ? format(next.from, DATE_TEXT) : "")
write("endDate", next?.to ? format(next.to, DATE_TEXT) : "")
if (time) {
if (next?.from && !form.getValues("startTime"))
write("startTime", "12:00 AM")
if (next?.to && !form.getValues("endTime")) write("endTime", "11:59 PM")
}
recheck()
}
function apply(values: Draft) {
const next = readDraft(values, time).range
if (!next) return
if (!controlled) setUncontrolled(next)
onValueChange?.(next)
setOpen(false)
}
// Clear empties the range straight away, with no Apply.
function clear() {
form.reset(toDraft(undefined, time))
if (!controlled) setUncontrolled(undefined)
onValueChange?.(undefined)
setOpen(false)
}
return (
<Field data-slot="date-range-picker" className={className} {...props}>
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Popover
open={open}
onOpenChange={(next) => {
// Opening starts again from the applied range.
if (next) {
form.reset(toDraft(range, time))
setMonth(range?.from ?? new Date())
}
setOpen(next)
}}
>
<PopoverTrigger
render={
<Button
variant="outline"
id={id}
className="justify-start px-2.5 font-normal"
/>
}
>
<CalendarBlankIcon data-icon="inline-start" />
{range?.from ? (
range.to ? (
<>
{format(range.from, dateFormat)} -{" "}
{format(range.to, dateFormat)}
</>
) : (
format(range.from, dateFormat)
)
) : (
<span>{placeholder}</span>
)}
</PopoverTrigger>
{/* 280px for one month, or the room the screen has: the popup
scrolls inside that, so nothing runs off a phone. More months
set their own width. */}
<PopoverContent
className={cn(
"max-h-(--available-height) max-w-(--available-width) overflow-y-auto",
numberOfMonths === 1 ? "w-70" : "w-auto"
)}
align="start"
>
<PopoverTitle className="sr-only">{label}</PopoverTitle>
{/* The calendar takes the popup's width, as the fields below do. */}
<Calendar
mode="range"
month={month}
onMonthChange={setMonth}
selected={shownFrom ? { from: shownFrom, to: shownTo } : undefined}
onSelect={pickDays}
numberOfMonths={numberOfMonths}
className="p-0"
classNames={{ root: "w-full" }}
/>
<form
className="grid gap-3"
noValidate
onSubmit={(event) => {
// The popup is a portal, so React would pass this submit on to
// a form the picker sits in. It ends here.
event.stopPropagation()
void form.handleSubmit(apply)(event)
}}
>
<Field data-invalid={startWrong}>
<FieldLabel htmlFor={`${id}-start`}>{COPY.start}</FieldLabel>
<div className="flex gap-2">
<Controller
control={form.control}
name="startDate"
render={({ field, fieldState }) => (
<Input
{...field}
id={`${id}-start`}
placeholder={COPY.datePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
startWrong ? `${id}-start-error` : undefined
}
onChange={(event) => {
field.onChange(event)
recheck()
// The calendar follows a date as soon as it reads.
const day = readDate(event.target.value)
if (day) setMonth(day)
}}
/>
)}
/>
{time ? (
<Controller
control={form.control}
name="startTime"
render={({ field, fieldState }) => (
<Input
{...field}
onChange={(event) => {
field.onChange(event)
recheck()
}}
aria-label={COPY.startTime}
placeholder={COPY.timePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
startWrong ? `${id}-start-error` : undefined
}
className="w-36"
/>
)}
/>
) : null}
</div>
<FieldError id={`${id}-start-error`} errors={startErrors} />
</Field>
<Field data-invalid={endWrong}>
<FieldLabel htmlFor={`${id}-end`}>{COPY.end}</FieldLabel>
<div className="flex gap-2">
<Controller
control={form.control}
name="endDate"
render={({ field, fieldState }) => (
<Input
{...field}
id={`${id}-end`}
onChange={(event) => {
field.onChange(event)
recheck()
}}
placeholder={COPY.datePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
endWrong ? `${id}-end-error` : undefined
}
/>
)}
/>
{time ? (
<Controller
control={form.control}
name="endTime"
render={({ field, fieldState }) => (
<Input
{...field}
onChange={(event) => {
field.onChange(event)
recheck()
}}
aria-label={COPY.endTime}
placeholder={COPY.timePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
endWrong ? `${id}-end-error` : undefined
}
className="w-36"
/>
)}
/>
) : null}
</div>
<FieldError id={`${id}-end-error`} errors={endErrors} />
</Field>
<div className="flex gap-2">
<Button
type="button"
variant="ghost"
disabled={!range?.from && !anyText}
onClick={clear}
>
{COPY.clear}
</Button>
<Button type="submit" variant="outline" className="flex-1">
{COPY.apply}
<Kbd aria-hidden="true">↵</Kbd>
</Button>
</div>
</form>
</PopoverContent>
</Popover>
</Field>
)
}
export { DateRangePicker }
Installation
npx shadcn@latest add @01orbital/date-range-picker-cardAPI reference
A date range field in a card: a label and a button showing the chosen range, which opens a calendar with typed start and end dates. It starts with January 20 to February 9, 2026 selected.
The label and placeholder live in COPY; the start date is START.
Prop
Type
Make it yours
- Its words are in
COPYat the top ofcomponents/blocks/controls/date-range-picker-card/index.tsx: change them there, not in the markup. START, also at the top of the file, holds its lists and settings.
Built from
npm: date-fns. The CLI installs it for you.
Built from these parts. The CLI adds each one that is missing and won't replace a file you already have unless you choose to:
The shadcn parts here are their Base UI versions, and this piece uses Base UI's API. A Radix version you already have won't work with it.
Last updated on