Components
Time Field
A field for a time of day, typed one part at a time: hours, minutes and seconds. Built on react-aria-components.
Introduction
Time Field is for a time of day: when a meeting starts, an alarm, an opening hour. The user types it part by part, so it is faster and harder to get wrong than a plain text box, and it shows the time the way their language does, on a 12 or a 24 hour clock.
- Each part is its own segment. Typing fills it and moves on, and the arrow keys step it up and down.
- Show hours only, hours and minutes, or seconds too, on a 12 or a 24 hour clock.
minValueandmaxValuemark a time outside the range as invalid as it is typed.- The value is plain text such as
"14:30", and it works in a form.
A time has no date and no time zone. For a date, use Date Field.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Time Field also needs @internationalized/date, which react-aria uses for times.
# bun
bun add react-aria-components @internationalized/date tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components @internationalized/date tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components @internationalized/date tailwind-variants tailwind-merge clsxManual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/time-field-styles.tsShow code
import { tv } from "tailwind-variants";
// The frame holds the clock icon and the segments (hours, minutes, ...). The
// focus ring wraps all of it, and the segment that has focus is highlighted.
export const timeFieldStyles = tv({
slots: {
frame: [
"flex w-full items-center gap-2 rounded-md text-fg transition-colors",
"focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
"group-data-invalid/time-field:border-danger",
"group-data-disabled/time-field:opacity-50",
"[&_svg]:shrink-0",
],
input: "flex min-w-0 flex-1 items-center",
segment: [
"rounded-[4px] px-0.5 tabular-nums caret-transparent outline-none",
"data-placeholder:text-muted-fg",
"data-focused:bg-primary data-focused:text-primary-fg data-focused:data-placeholder:text-primary-fg",
"data-[type=literal]:px-0",
"data-disabled:cursor-not-allowed",
],
icon: "text-muted-fg",
},
variants: {
variant: {
outline: { frame: "border bg-transparent" },
secondary: { frame: "bg-secondary text-secondary-fg" },
ghost: { frame: "bg-transparent focus-within:bg-muted hover:bg-muted" },
},
size: {
sm: { frame: "h-8 px-2.5 text-sm", icon: "size-4" },
md: { frame: "h-9 px-3 text-sm", icon: "size-4" },
lg: { frame: "h-11 px-3.5 text-base", icon: "size-5" },
},
},
defaultVariants: { variant: "outline", size: "md" },
});2. Add the Time Field file
src/components/ui/time-field/time-field.tsxShow code
"use client";
import { parseTime, type Time } from "@internationalized/date";
import { type ReactNode, useMemo, useRef, useSyncExternalStore } from "react";
import {
TimeField as AriaTimeField,
type TimeFieldProps as AriaTimeFieldProps,
DateInput,
DateSegment,
FieldError,
Label,
Text,
type TimeValue,
type ValidationResult,
} from "react-aria-components";
import { ClockIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import { timeFieldStyles } from "@/types/time-field-styles";
type Granularity = "hour" | "minute" | "second";
export interface TimeFieldProps
extends Omit<
AriaTimeFieldProps<Time>,
| "children"
| "className"
| "value"
| "defaultValue"
| "onChange"
| "minValue"
| "maxValue"
| "placeholderValue"
| "granularity"
> {
label?: ReactNode;
/** Help text under the field. */
description?: ReactNode;
/** Shown when the field is invalid. A function receives the validation result. */
errorMessage?: string | ((validation: ValidationResult) => string);
/** The time as text, `"14:30"`, or `null` while it is not complete. For a controlled field. */
value?: string | null;
/** The time to start with, as text such as `"14:30"`. For an uncontrolled field. */
defaultValue?: string | null;
onChange?: (value: string | null) => void;
/** The earliest time that is valid, such as `"09:00"`. */
minValue?: string;
/** The latest time that is valid, such as `"17:00"`. */
maxValue?: string;
/** The smallest part shown: hours, minutes (default) or seconds. */
granularity?: Granularity;
/** Show the time on a 12 or a 24 hour clock. Defaults to the user's language. */
hourCycle?: 12 | 24;
/** Replaces the clock icon. `null` shows none. */
icon?: ReactNode;
variant?: "outline" | "secondary" | "ghost";
size?: "sm" | "md" | "lg";
className?: string;
}
function toTime(text: string | null | undefined) {
if (!text) return null;
try {
return parseTime(text);
} catch {
return null;
}
}
const pad = (n: number) => String(n).padStart(2, "0");
// `Time` becomes text: "14:30", or "14:30:15" when seconds are shown.
function toText(time: TimeValue | null, granularity: Granularity) {
if (!time) return null;
const text = `${pad(time.hour)}:${pad(time.minute)}`;
return granularity === "second" ? `${text}:${pad(time.second)}` : text;
}
/**
* A field for a time of day, typed one part at a time: hours, minutes and, if
* you ask for them, seconds and AM or PM. Each part is its own segment: type
* digits, or use the arrow keys, and focus moves to the next one by itself. Built
* on react-aria's TimeField, so keyboard support, screen reader support,
* the 12 or 24 hour clock of the user's language and form submission (`name`)
* come from there.
*
* The value is plain text, `"14:30"` (24 hour, always), which is what a form
* and a database want. It is `null` until every part is filled. A time has no
* date and no time zone.
*
* @example
* <TimeField label="Opens at" defaultValue="09:00" onChange={setOpensAt} />
*/
export function TimeField({
label,
description,
errorMessage,
value,
defaultValue,
onChange,
minValue,
maxValue,
granularity = "minute",
hourCycle,
icon,
variant,
size = "md",
className,
...props
}: TimeFieldProps) {
const styles = timeFieldStyles({ variant, size });
// False on the server and while the page hydrates, true after.
const isClient = useSyncExternalStore(
() => () => {},
() => true,
() => false,
);
const frameRef = useRef<HTMLDivElement>(null);
const isControlled = value !== undefined;
const controlled = useMemo(() => toTime(value), [value]);
const initial = useMemo(() => toTime(defaultValue), [defaultValue]);
const min = useMemo(() => toTime(minValue) ?? undefined, [minValue]);
const max = useMemo(() => toTime(maxValue) ?? undefined, [maxValue]);
return (
<AriaTimeField
{...props}
{...(isControlled ? { value: controlled } : { defaultValue: initial })}
onChange={(next) => onChange?.(toText(next, granularity))}
minValue={min}
maxValue={max}
granularity={granularity}
hourCycle={hourCycle}
// Show a problem while the user types, not only on submit.
validationBehavior="aria"
className={cn("group/time-field flex w-full flex-col gap-1.5", className)}
>
{label ? (
<Label className="text-sm font-medium group-data-required/time-field:after:ml-0.5 group-data-required/time-field:after:text-danger group-data-required/time-field:after:content-['*']">
{label}
</Label>
) : null}
{/* biome-ignore lint/a11y/noStaticElementInteractions: a mouse shortcut, the segments are still reachable by keyboard */}
<div
ref={frameRef}
className={styles.frame()}
// Clicking the empty space of the frame focuses the first segment.
onMouseDown={(event) => {
if ((event.target as HTMLElement).closest('[role="spinbutton"]'))
return;
event.preventDefault();
frameRef.current
?.querySelector<HTMLElement>('[role="spinbutton"]')
?.focus();
}}
>
{icon === null ? null : (
<span aria-hidden="true" className={styles.icon()}>
{icon ?? <ClockIcon />}
</span>
)}
{isClient ? (
<DateInput className={styles.input()}>
{(segment) => (
<DateSegment segment={segment} className={styles.segment()} />
)}
</DateInput>
) : (
// The segments are written in the user's language, and the server
// and the browser can spell them differently (the space before AM
// or PM is a different character). So they are drawn in the browser
// only, and the frame keeps its place until then.
<div aria-hidden="true" className={styles.input()} />
)}
</div>
{description ? (
<Text slot="description" className="text-sm text-muted-fg">
{description}
</Text>
) : null}
<FieldError className="text-sm text-danger">{errorMessage}</FieldError>
</AriaTimeField>
);
}It imports ClockIcon from @/components/icons. Add that icon, or swap it for your own.
3. Use it
import { TimeField } from "@/components/ui/time-field/time-field";Anatomy
A framed row of segments with a clock in front.
<TimeField
label="Opens at"
description="Local time."
defaultValue="09:00"
minValue="06:00"
maxValue="22:00"
/>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the field. Clicking it focuses the first segment. |
| Icon | svg | A clock. Replace it with the icon prop, or remove it with icon={null}. |
| Segments | spinbutton | Hours, minutes, seconds and AM or PM, each one its own control, with colons between them. The one with focus is highlighted. |
| Description / error | text under the field | Help text, replaced by the error message when the field is invalid. |
Without a label, give the field an aria-label so a screen reader can name it.
Value
The time is text in 24 hour form, whatever clock the field shows.
// The value is text. It is always 24 hour, whatever the field shows.
"09:30" // 9:30 AM
"14:45" // 2:45 PM
"14:45:10" // with granularity="second"
null // not complete yetThe value is null until the hours and the minutes (and the seconds, if you show them) are all filled, so an unfinished time is never reported as a wrong one. In a 12 hour field, AM or PM is chosen for you when the hour makes it clear, and can be changed with the A and P keys.
Keyboard
Every segment is a control of its own. These keys work while one has focus.
| Key | What it does |
|---|---|
| Type digits | Fill the segment that has focus. Focus moves to the next one when the segment is full. |
| Arrow Up, Arrow Down | Add or subtract one from the segment. Page Up and Page Down step by more. |
| Arrow Left, Arrow Right | Move to the previous or the next segment. |
| A or P | Choose AM or PM in a 12 hour field. |
| Backspace | Remove the last digit of the segment. When it is empty, the segment shows its placeholder again. |
Examples
Click a segment and type, or use the arrow keys.
Usage
Label
Every field needs a name. Use label, or aria-label when the label is written elsewhere.
Description
Help text under the field.
Default value
Start with a time, written as text.
Granularity
The smallest part the field shows: hours only, minutes (the default) or seconds.
Hour cycle
By default the field follows the user's language. Force a 12 hour clock, with AM and PM, or a 24 hour one. The value is the same either way.
Minimum and maximum
A time outside the range is marked invalid as it is typed, with a message in the user's language.
Icon
A clock by default. Use icon for another one, or icon={null} for none.
Controlled
Keep the time in your own state with value and onChange. The value is null while the time is not complete, for example after it is cleared.
value: "09:30"
In a form
With a name, the time is submitted as one field, in 24 hour time with seconds, such as 07:15:00.
Read only
The time can be seen and focused, but not changed.
Sizes
Variants
Disabled
Validation
minValue and maxValue cover a simple range. For a rule of your own, set isInvalid with an errorMessage. The field gets a red border and the message shows under it.
Component API
Time Field takes the props below, plus most of what the react-aria TimeField accepts.
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - |
| description | ReactNode | - |
| errorMessage | string | (validation) => string | - |
| value | string | null | - |
| defaultValue | string | null | - |
| onChange | (value: string | null) => void | - |
| minValue | string | - |
| maxValue | string | - |
| granularity | "hour" | "minute" | "second" | "minute" |
| hourCycle | 12 | 24 | the language's |
| icon | ReactNode | null | a clock |
| name | string | - |
| variant | "outline" | "secondary" | "ghost" | "outline" |
| size | "sm" | "md" | "lg" | "md" |
| autoFocus | boolean | false |
| isDisabled | boolean | false |
| isReadOnly | boolean | false |
| isInvalid | boolean | false |
| isRequired | boolean | false |
| aria-label | string | - (when there is no label) |