Menu

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.
  • minValue and maxValue mark 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 clsx

Manual 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"
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the first segment.
IconsvgA clock. Replace it with the icon prop, or remove it with icon={null}.
SegmentsspinbuttonHours, minutes, seconds and AM or PM, each one its own control, with colons between them. The one with focus is highlighted.
Description / errortext under the fieldHelp 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 yet

The 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.

KeyWhat it does
Type digitsFill the segment that has focus. Focus moves to the next one when the segment is full.
Arrow Up, Arrow DownAdd or subtract one from the segment. Page Up and Page Down step by more.
Arrow Left, Arrow RightMove to the previous or the next segment.
A or PChoose AM or PM in a 12 hour field.
BackspaceRemove 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

Meeting starts

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Meeting starts
Meeting starts

Description

Help text under the field.

Meeting starts
In your local time.

Default value

Start with a time, written as text.

Alarm

Granularity

The smallest part the field shows: hours only, minutes (the default) or seconds.

Hours
Minutes (default)
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.

12 hour
24 hour

Minimum and maximum

A time outside the range is marked invalid as it is typed, with a message in the user's language.

Opening time
Between 06:00 and 22:00.Value must be 10:00 PM or earlier.

Icon

A clock by default. Use icon for another one, or icon={null} for none.

Default icon
Another icon
No icon

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.

Meeting starts

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.

Alarm

Not submitted yet.

Read only

The time can be seen and focused, but not changed.

Checked in

Sizes

Variants

Disabled

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.

Delivery time
Deliveries are between 06:00 and 22:00.We do not deliver before 06:00.

Component API

Time Field takes the props below, plus most of what the react-aria TimeField accepts.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
valuestring | null-
defaultValuestring | null-
onChange(value: string | null) => void-
minValuestring-
maxValuestring-
granularity"hour" | "minute" | "second""minute"
hourCycle12 | 24the language's
iconReactNode | nulla clock
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg""md"
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)