본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

TimeField

원문 보기 위키 갱신

React Aria TimeField를 기반으로 라벨, 설명, 검증을 갖춘 시간 입력 필드 컴포넌트입니다. 시간을 입력하고 검증해야 하는 폼에 사용하세요.

출처: HeroUI page-name

본문

사용법 (Usage)

import { TimeField } from '@heroui/react';
"time-field-basic"

구조 (Anatomy)

import {TimeField, Label, Description, FieldError} from '@heroui/react';

export default () => (
  <TimeField>
    <Label />
    <TimeField.Group>
      <TimeField.Input>
        {(segment) => <TimeField.Segment segment={segment} />}
      </TimeField.Input>
    </TimeField.Group>
    <Description />
    <FieldError />
  </TimeField>
)

TimeField는 라벨, 시간 입력, 설명, 오류를 하나의 접근성(accessible) 있는 컴포넌트로 결합합니다.

예제 (Examples)

아이콘과 함께 (With Icons)

시간 필드를 돋보이게 하려면 접두사(prefix) 또는 접미사(suffix) 아이콘을 추가할 수 있습니다.

"time-field-with-prefix-icon"
"time-field-with-suffix-icon"
"time-field-with-prefix-and-suffix"

표면 위에서 (On Surface)

Surface 컴포넌트 안에서 사용할 때는 TimeField.Group에 variant="secondary"를 사용해서 표면 배경에 적합한 낮은 강조(lower emphasis) 변형을 적용하세요.

"time-field-on-surface"

설명과 함께 (With Description)

"time-field-with-description"

필수 필드 (Required Field)

"time-field-required"

비활성 상태 (Disabled State)

"time-field-disabled"

전체 너비 (Full Width)

"time-field-full-width"

검증 (Validation)

isInvalid을 FieldError와 함께 사용해서 검증 메시지를 표시할 수 있습니다.

"time-field-invalid"

제어 (Controlled)

값을 제어해서 다른 컴포넌트나 상태 관리와 동기화할 수 있습니다.

"time-field-controlled"

폼 예제 (Form Example)

검증과 제출 처리를 포함한 완전한 폼 예제입니다.

"time-field-form-example"

검증과 함께 (With Validation)

TimeField는 minValue, maxValue 및 커스텀 검증 로직을 지원합니다.

"time-field-with-validation"

렌더 함수 (Render Function)

"time-field-render-function"

커스터마이징 (Customization)

Tailwind CSS

"time-field-custom-styles"

Global CSS

TimeField는 최소한의 기본 스타일을 가지고 있습니다. .time-field 클래스를 재정의해서 컨테이너 스타일을 커스터마이징하세요.

@layer components {
  .time-field {
    @apply flex flex-col gap-1;

    &[data-invalid="true"],
    &[aria-invalid="true"] {
      [data-slot="description"] {
        @apply hidden;
      }
    }

    [data-slot="label"] {
      @apply w-fit;
    }

    [data-slot="description"] {
      @apply px-1;
    }
  }
}

스타일링 참조 (Styling Reference)

HeroUI는 BEM 방법론을 따르므로 컴포넌트 변형과 상태를 재사용하고 커스터마이징하기 쉽습니다.

CSS 클래스

  • .time-field – 최소한의 스타일(flex flex-col gap-1)을 가진 루트 컨테이너

참고: 자식 컴포넌트(Label, Description, FieldError)는 각자 자체 CSS 클래스와 스타일을 가집니다. 커스터마이징 옵션은 각 문서를 참조하세요. TimeField.Group 스타일링은 아래 API 참조 섹션에 문서화되어 있습니다.

상호작용 상태 (Interactive States)

TimeField는 상태에 따라 다음 데이터 속성(data attributes)을 자동으로 관리합니다:

  • 유효하지 않음 (Invalid): [data-invalid="true"] 또는 [aria-invalid="true"] - 유효하지 않을 때 설명 슬롯을 자동으로 숨깁니다
  • 필수 (Required): [data-required="true"] - isRequired가 true일 때 적용됩니다
  • 비활성 (Disabled): [data-disabled="true"] - isDisabled가 true일 때 적용됩니다
  • 포커스 포함 (Focus Within): [data-focus-within="true"] - 자식 입력에 포커스가 있을 때 적용됩니다

API 참조 (API Reference)

TimeField

TimeField는 React Aria의 TimeField 컴포넌트의 모든 props를 상속받습니다.

기본 Props (Base Props)

Prop Type Default Description
children React.ReactNode | (values: TimeFieldRenderProps) => React.ReactNode - 자식 컴포넌트 (Label, TimeField.Group 등) 또는 렌더 함수.
className string | (values: TimeFieldRenderProps) => string - 스타일링을 위한 CSS 클래스, 렌더 props 지원.
style React.CSSProperties | (values: TimeFieldRenderProps) => React.CSSProperties - 인라인 스타일, 렌더 props 지원.
fullWidth boolean false 시간 필드가 컨테이너의 전체 너비를 차지할지 여부
id string - 요소의 고유 식별자.
render DOMRenderFunction<keyof React.JSX.IntrinsicElements, TimeFieldRenderProps> - 기본 DOM 요소를 커스텀 렌더 함수로 재정의합니다.

값 Props (Value Props)

Prop Type Default Description
value TimeValue | null - 현재 값 (제어). @internationalized/date 타입을 사용합니다.
defaultValue TimeValue | null - 기본 값 (비제어). @internationalized/date 타입을 사용합니다.
onChange (value: TimeValue | null) => void - 값이 변경될 때 호출되는 핸들러.
placeholderValue TimeValue | null - 플레이스홀더 형식에 영향을 주는 플레이스홀더 시간. 시간 주기(hour cycle)에 따라 기본값이 12:00 AM 또는 00:00입니다.

검증 Props (Validation Props)

Prop Type Default Description
isRequired boolean false 폼 제출 전에 사용자 입력이 필요한지 여부.
isInvalid boolean - 값이 유효하지 않은지 여부.
minValue TimeValue | null - 사용자가 선택할 수 있는 최소 허용 시간. @internationalized/date 타입을 사용합니다.
maxValue TimeValue | null - 사용자가 선택할 수 있는 최대 허용 시간. @internationalized/date 타입을 사용합니다.
validate (value: TimeValue) => ValidationError | true | null | undefined - 커스텀 검증 함수.
validationBehavior 'native' | 'aria' 'native' 네이티브 HTML 폼 검증을 사용할지 ARIA 속성을 사용할지 여부.

형식 Props (Format Props)

Prop Type Default Description
granularity 'hour' | 'minute' | 'second' 'minute' 시간 선택기에 표시되는 가장 작은 단위를 결정합니다.
hourCycle 12 | 24 - 시간을 12시간 또는 24시간 형식으로 표시할지 여부. 기본값은 로케일에 따라 결정됩니다.
hideTimeZone boolean false 시간대 약어를 숨길지 여부.
shouldForceLeadingZeros boolean - 시간 필드에 항상 앞자리 0을 표시할지 여부. 기본값은 로케일에 따라 결정됩니다.

상태 Props (State Props)

Prop Type Default Description
isDisabled boolean - 입력이 비활성화되었는지 여부.
isReadOnly boolean - 입력을 선택할 수는 있지만 변경할 수는 없는지 여부.

폼 Props (Form Props)

Prop Type Default Description
name string - HTML 폼 제출을 위한 입력 요소의 이름. ISO 8601 문자열로 제출됩니다.
autoFocus boolean - 요소가 렌더링 시 포커스를 받을지 여부.

접근성 Props (Accessibility Props)

Prop Type Default Description
aria-label string - 표시되는 라벨이 없을 때의 접근성 라벨.
aria-labelledby string - 이 필드에 라벨을 지정하는 요소들의 ID.
aria-describedby string - 이 필드를 설명하는 요소들의 ID.
aria-details string - 추가 세부 정보를 가진 요소들의 ID.

구성 컴포넌트 (Composition Components)

TimeField는 별도로 가져와 직접 사용해야 하는 다음 컴포넌트들과 함께 동작합니다:

  • Label - @heroui/react의 필드 라벨 컴포넌트
  • TimeField.Group - 시간 입력 그룹 컴포넌트 (아래에 문서화)
  • TimeField.Input - 세그먼트 편집이 가능한 @heroui/react의 입력 컴포넌트
  • TimeField.Segment - 개별 시간 세그먼트 (시, 분, 초 등)
  • TimeField.Prefix / TimeField.Suffix - 입력 그룹의 접두사 및 접미사 슬롯
  • Description - @heroui/react의 도움말 텍스트 컴포넌트
  • FieldError - @heroui/react의 검증 오류 메시지

이 각 컴포넌트는 고유한 props API를 가집니다. TimeField 안에서 직접 사용해서 구성해 보세요:

import {parseTime} from '@internationalized/date';
import {TimeField, Label, Description, FieldError} from '@heroui/react';

<TimeField
  isRequired
  isInvalid={hasError}
  minValue={parseTime('09:00')}
  maxValue={parseTime('17:00')}
  value={time}
  onChange={setTime}
>
  <Label>Appointment Time</Label>
  <TimeField.Group>
    <TimeField.Input>
      {(segment) => <TimeField.Segment segment={segment} />}
    </TimeField.Input>
  </TimeField.Group>
  <Description>Select a time between 9:00 AM and 5:00 PM.</Description>
  <FieldError>Please select a valid time.</FieldError>
</TimeField>

TimeValue 타입

TimeField는 @internationalized/date의 타입을 사용합니다:

  • Time - 시간만 포함 (시, 분, 초)
  • CalendarDateTime - 시간대가 없는 날짜+시간 (TimeField는 시간 부분만 표시합니다)
  • ZonedDateTime - 시간대가 있는 날짜+시간 (TimeField는 시간 부분만 표시합니다)

예시:

import {parseTime, Time, getLocalTimeZone, now} from '@internationalized/date';

// Parse from string
const time = parseTime('14:30');

// Create from current time
const currentTime = now(getLocalTimeZone());
const timeValue = new Time(currentTime.hour, currentTime.minute, currentTime.second);

// Use in TimeField
<TimeField value={time} onChange={setTime}>
  {/* ... */}
</TimeField>

참고: TimeField는 시간 조작, 파싱, 타입 정의를 위해 @internationalized/date 패키지를 사용합니다. 사용 가능한 타입과 함수에 대한 자세한 내용은 Internationalized Date 문서를 참조하세요.

렌더 Props (Render Props)

className, style 또는 children에서 렌더 props를 사용할 때 다음 값들이 제공됩니다:

Prop Type Description
isDisabled boolean 필드가 비활성화되었는지 여부.
isInvalid boolean 필드가 현재 유효하지 않은지 여부.
isReadOnly boolean 필드가 읽기 전용인지 여부.
isRequired boolean 필드가 필수인지 여부.
isFocused boolean 필드가 현재 포커스되었는지 여부.
isFocusWithin boolean 자식 요소 중 하나가 포커스되었는지 여부.
isFocusVisible boolean 포커스가 표시되는지 여부 (키보드 탐색).

TimeField.Group

TimeField.Group은 React Aria의 Group 컴포넌트의 모든 props를 받으며 아래 항목도 추가로 받습니다:

Prop Type Default Description
className string - 컴포넌트 스타일에 병합되는 Tailwind 클래스.
variant "primary" | "secondary" "primary" 컴포넌트의 시각적 변형. primary는 그림자가 있는 기본 스타일입니다. secondary는 그림자가 없는 낮은 강조 변형으로 표면(surface)에서 사용하기 적합합니다.

TimeField.Input

TimeField.Input은 React Aria의 DateInput 컴포넌트의 모든 props를 받으며 아래 항목도 추가로 받습니다:

Prop Type Default Description
className string - 컴포넌트 스타일에 병합되는 Tailwind 클래스.
variant "primary" | "secondary" "primary" 입력의 시각적 변형. primary는 그림자가 있는 기본 스타일입니다. secondary는 그림자가 없는 낮은 강조 변형으로 표면(surface)에서 사용하기 적합합니다.

TimeField.Input 컴포넌트는 날짜 세그먼트를 받는 렌더 prop 함수를 허용합니다. 각 세그먼트는 시간의 일부(시, 분, 초 등)를 나타냅니다.

TimeField.Segment

TimeField.Segment는 React Aria의 DateSegment 컴포넌트의 모든 props를 받습니다:

Prop Type Default Description
segment DateSegment - TimeField.Input 렌더 prop의 날짜 세그먼트 객체.
className string - 컴포넌트 스타일에 병합되는 Tailwind 클래스.

TimeField.Prefix

TimeField.Prefix는 표준 HTML div 속성을 받습니다:

Prop Type Default Description
className string - 컴포넌트 스타일에 병합되는 Tailwind 클래스.
children ReactNode - 접두사 슬롯에 표시할 콘텐츠.

TimeField.Suffix

TimeField.Suffix는 표준 HTML div 속성을 받습니다:

Prop Type Default Description
className string - 컴포넌트 스타일에 병합되는 Tailwind 클래스.
children ReactNode - 접미사 슬롯에 표시할 콘텐츠.

TimeField.Group 스타일링

컴포넌트 클래스 커스터마이징

기본 클래스는 모든 인스턴스를 구동합니다. @layer components로 한 번만 재정의하면 됩니다.

@layer components {
  .date-input-group {
    @apply inline-flex h-9 items-center overflow-hidden rounded-field border bg-field text-sm text-field-foreground shadow-field outline-none;

    &:hover,
    &[data-hovered="true"] {
      @apply bg-field-hover;
    }

    &[data-focus-within="true"],
    &:focus-within {
      @apply status-focused-field;
    }

    &[data-invalid="true"] {
      @apply status-invalid-field;
    }

    &[data-disabled="true"],
    &[aria-disabled="true"] {
      @apply status-disabled;
    }
  }

  .date-input-group__input {
    @apply flex flex-1 items-center gap-px rounded-none border-0 bg-transparent px-3 py-2 shadow-none outline-none;
  }

  .date-input-group__segment {
    @apply inline-block rounded-md px-0.5 text-end tabular-nums outline-none;

    &:focus,
    &[data-focused="true"] {
      @apply bg-accent-soft text-accent-soft-foreground;
    }
  }

  .date-input-group__prefix,
  .date-input-group__suffix {
    @apply pointer-events-none shrink-0 text-field-placeholder flex items-center;
  }
}

TimeField.Group CSS 클래스

  • .date-input-group – 루트 컨테이너 스타일링
  • .date-input-group__input – 입력 래퍼 스타일링
  • .date-input-group__segment – 개별 시간 세그먼트 스타일링
  • .date-input-group__prefix – 접두사 요소 스타일링
  • .date-input-group__suffix – 접미사 요소 스타일링

TimeField.Group 상호작용 상태

  • 호버 (Hover): :hover 또는 [data-hovered="true"]
  • 포커스 포함 (Focus Within): [data-focus-within="true"] 또는 :focus-within
  • 유효하지 않음 (Invalid): [data-invalid="true"] (aria-invalid와도 동기화됨)
  • 비활성 (Disabled): [data-disabled="true"] 또는 [aria-disabled="true"]
  • 세그먼트 포커스 (Segment Focus): 세그먼트 요소의 :focus 또는 [data-focused="true"]
  • 세그먼트 플레이스홀더 (Segment Placeholder): 세그먼트 요소의 [data-placeholder="true"]

더 알아보기 (Learn more)