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

DateField

원문 보기 위키 갱신

React Aria DateField를 기반으로 라벨, 설명, 검증 기능을 갖춘 날짜 입력 필드예요.

출처: HeroUI DateField

본문

사용법 (Usage)

import { DateField } from '@heroui/react';
{"component": "date-field-basic"}

구조 (Anatomy)

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

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

DateField은 라벨, 날짜 입력, 설명, 오류를 하나의 접근 가능한 컴포넌트로 결합해요.

예시 (Examples)

아이콘 포함 (With Icons)

날짜 필드를 보완하려면 접두사 또는 접미사 아이콘을 추가하세요.

{"component": "date-field-with-prefix-icon"}
{"component": "date-field-with-suffix-icon"}
{"component": "date-field-with-prefix-and-suffix"}

변형 (Variants)

DateField.Group 컴포넌트는 두 가지 시각적 변형을 지원해요:

  • primary (기본값) - 그림자가 있는 표준 스타일, 대부분의 사용 사례에 적합
  • secondary - 그림자가 없는 낮은 강조 변형, Surface 컴포넌트에서 사용하기 적합
{"component": "date-field-variants"}

서피스 내에서 (In Surface)

Surface 컴포넌트 안에서 사용할 때는 DateField.Group에 variant="secondary" 를 사용해서 서피스 배경에 어울리는 낮은 강조 변형을 적용하세요.

{"component": "date-field-on-surface"}

설명 포함 (With Description)

{"component": "date-field-with-description"}

필수 필드 (Required Field)

{"component": "date-field-required"}

비활성화 상태 (Disabled State)

{"component": "date-field-disabled"}

전체 너비 (Full Width)

{"component": "date-field-full-width"}

검증 (Validation)

isInvalid 을 FieldError 와 함께 사용해서 검증 메시지를 표시하세요.

{"component": "date-field-invalid"}

세분성 (Granularity)

{"component": "date-field-granularity"}

제어 (Controlled)

다른 컴포넌트나 상태 관리와 동기화하려면 값을 제어하세요.

{"component": "date-field-controlled"}

폼 예시 (Form Example)

검증과 제출 처리를 포함한 완전한 폼 예시예요.

{"component": "date-field-form-example"}

검증 포함 (With Validation)

DateField는 minValue, maxValue, 그리고 커스텀 검증 로직으로 검증을 지원해요.

{"component": "date-field-with-validation"}

렌더 함수 (Render Function)

{"component": "date-field-render-function"}

커스터마이징 (Customization)

Tailwind CSS

{"component": "date-field-custom-styles"}

전역 CSS (Global CSS)

DateField는 최소한의 기본 스타일을 가져요. 컨테이너 스타일을 커스터마이징하려면 .date-field 클래스를 재정의하세요.

@layer components {
  .date-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 클래스 (CSS Classes)

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

참고: 자식 컴포넌트(Label, Description, FieldError)는 고유한 CSS 클래스와 스타일을 가져요. 커스터마이징 옵션은 각각의 문서를 참고하세요. DateField.Group 스타일링은 아래 API Reference 섹션에서 설명해요.

인터랙티브 상태 (Interactive States)

DateField는 상태에 따라 다음 데이터 속성을 자동으로 관리해요:

  • 유효하지 않음: [data-invalid="true"] 또는 [aria-invalid="true"] - 유효하지 않을 때 설명 슬롯을 자동으로 숨겨요
  • 필수: [data-required="true"] - isRequired가 true일 때 적용돼요
  • 비활성화: [data-disabled="true"] - isDisabled가 true일 때 적용돼요
  • 포커스 내부: [data-focus-within="true"] - 자식 입력 중 하나에 포커스가 있을 때 적용돼요

API 참고 (API Reference)

DateField

DateField는 React Aria의 DateField 컴포넌트에서 모든 프롭을 상속받아요.

기본 프롭 (Base Props)

Prop Type Default Description
children React.ReactNode | (values: DateFieldRenderProps) => React.ReactNode - Child components (Label, DateField.Group, etc.) or render function.
className string | (values: DateFieldRenderProps) => string - CSS classes for styling, supports render props.
style React.CSSProperties | (values: DateFieldRenderProps) => React.CSSProperties - Inline styles, supports render props.
fullWidth boolean false Whether the date field should take full width of its container
id string - The element's unique identifier.
render DOMRenderFunction<keyof React.JSX.IntrinsicElements, DateFieldRenderProps> - Overrides the default DOM element with a custom render function.

값 프롭 (Value Props)

Prop Type Default Description
value DateValue | null - Current value (controlled). Uses @internationalized/date types.
defaultValue DateValue | null - Default value (uncontrolled). Uses @internationalized/date types.
onChange (value: DateValue | null) => void - Handler called when the value changes.
placeholderValue DateValue | null - Placeholder date that influences the format of the placeholder.

검증 프롭 (Validation Props)

Prop Type Default Description
isRequired boolean false Whether user input is required before form submission.
isInvalid boolean - Whether the value is invalid.
minValue DateValue | null - The minimum allowed date that a user may select. Uses @internationalized/date types.
maxValue DateValue | null - The maximum allowed date that a user may select. Uses @internationalized/date types.
isDateUnavailable (date: DateValue) => boolean - Callback that is called for each date. If it returns true, the date is unavailable.
validate (value: DateValue) => ValidationError | true | null | undefined - Custom validation function.
validationBehavior 'native' | 'aria' 'native' Whether to use native HTML form validation or ARIA attributes.

형식 프롭 (Format Props)

Prop Type Default Description
granularity Granularity - Determines the smallest unit displayed. Defaults to "day" for dates, "minute" for times.
hourCycle 12 | 24 - Whether to display time in 12 or 24 hour format. By default, determined by locale.
hideTimeZone boolean false Whether to hide the time zone abbreviation.
shouldForceLeadingZeros boolean - Whether to always show leading zeros in month, day, and hour fields.

상태 프롭 (State Props)

Prop Type Default Description
isDisabled boolean - Whether the input is disabled.
isReadOnly boolean - Whether the input can be selected but not changed.

폼 프롭 (Form Props)

Prop Type Default Description
name string - Name of the input element, for HTML form submission. Submits as ISO 8601 string.
autoFocus boolean - Whether the element should receive focus on render.
autoComplete string - Type of autocomplete functionality the input should provide.

접근성 프롭 (Accessibility Props)

Prop Type Default Description
aria-label string - Accessibility label when no visible label is present.
aria-labelledby string - ID of elements that label this field.
aria-describedby string - ID of elements that describe this field.
aria-details string - ID of elements with additional details.

구성 컴포넌트 (Composition Components)

DateField은 다음 분리된 컴포넌트들과 함께 동작하며, 이들을 직접 임포트해서 사용해야 해요:

  • Label - @heroui/react의 필드 라벨 컴포넌트
  • DateField.Group - 날짜 입력 그룹 컴포넌트 (아래에 설명)
  • DateField.Input - @heroui/react의 세그먼트 편집이 있는 입력 컴포넌트
  • DateField.InputContainer - 여러 입력(예: 시작/끝 범위 입력)을 가로 오버플로로 그룹화하는 스크롤 가능한 컨테이너
  • DateField.Segment - 개별 날짜 세그먼트 (년, 월, 일 등)
  • DateField.Prefix / DateField.Suffix - 입력 그룹의 접두사 및 접미사 슬롯
  • Description - @heroui/react의 도움말 텍스트 컴포넌트
  • FieldError - @heroui/react의 검증 오류 메시지

이 컴포넌트 각각은 고유한 프롭 API를 가져요. 합성을 위해 DateField 안에서 직접 사용하세요:

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

<DateField
  isRequired
  isInvalid={hasError}
  minValue={today(getLocalTimeZone())}
  value={date}
  onChange={setDate}
>
  <Label>Appointment Date</Label>
  <DateField.Group>
    <DateField.Input>
      {(segment) => <DateField.Segment segment={segment} />}
    </DateField.Input>
  </DateField.Group>
  <Description>Select a date from today onwards.</Description>
  <FieldError>Please select a valid date.</FieldError>
</DateField>

DateValue 타입 (DateValue Types)

DateField은 @internationalized/date의 타입을 사용해요:

  • CalendarDate - 시간이나 시간대가 없는 날짜
  • CalendarDateTime - 시간대가 없는 시간이 포함된 날짜
  • ZonedDateTime - 시간과 시간대가 포함된 날짜
  • Time - 시간만

예시:

import {parseDate, today, getLocalTimeZone} from '@internationalized/date';

// Parse from string
const date = parseDate('2024-01-15');

// Today's date
const todayDate = today(getLocalTimeZone());

// Use in DateField
<DateField value={date} onChange={setDate}>
  {/* ... */}
</DateField>

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

렌더 프롭스 (Render Props)

className, style, children과 함께 렌더 프롭스를 사용하면 다음 값이 제공돼요:

Prop Type Description
isDisabled boolean Whether the field is disabled.
isInvalid boolean Whether the field is currently invalid.
isReadOnly boolean Whether the field is read-only.
isRequired boolean Whether the field is required.
isFocused boolean Whether the field is currently focused.
isFocusWithin boolean Whether any child element is focused.
isFocusVisible boolean Whether focus is visible (keyboard navigation).

DateField.Group

DateField.Group은 React Aria의 Group 컴포넌트의 모든 프롭과 다음을 추가로 받아요:

Prop Type Default Description
className string - Tailwind classes merged with the component styles.
fullWidth boolean false Whether the date input group should take full width of its container
variant "primary" | "secondary" "primary" Visual variant of the component. primary is the default style with shadow. secondary is a lower emphasis variant without shadow, suitable for use in surfaces.

DateField.Input

DateField.Input은 React Aria의 DateInput 컴포넌트의 모든 프롭과 다음을 추가로 받아요:

Prop Type Default Description
className string - Tailwind classes merged with the component styles.
variant "primary" | "secondary" "primary" Visual variant of the input. primary is the default style with shadow. secondary is a lower emphasis variant without shadow, suitable for use in surfaces.

DateField.Input 컴포넌트는 날짜 세그먼트를 받는 렌더 프롭 함수를 지원해요. 각 세그먼트는 날짜의 한 부분(년, 월, 일 등)을 나타내요.

DateField.Segment

DateField.Segment는 React Aria의 DateSegment 컴포넌트의 모든 프롭을 받아요:

Prop Type Default Description
segment DateSegment - The date segment object from the DateField.Input render prop.
className string - Tailwind classes merged with the component styles.

DateField.InputContainer

DateField.InputContainer는 표준 HTML div 속성을 받아요:

Prop Type Default Description
className string - Tailwind classes merged with the component styles.
children ReactNode - Content to display inside the scrollable container (typically multiple DateField.Input components).

DateField.Prefix

DateField.Prefix는 표준 HTML div 속성을 받아요:

Prop Type Default Description
className string - Tailwind classes merged with the component styles.
children ReactNode - Content to display in the prefix slot.

DateField.Suffix

DateField.Suffix는 표준 HTML div 속성을 받아요:

Prop Type Default Description
className string - Tailwind classes merged with the component styles.
children ReactNode - Content to display in the suffix slot.

DateField.Group 스타일링 (Styling)

컴포넌트 클래스 커스터마이징 (Customizing the component classes)

기본 클래스는 모든 인스턴스에 적용돼요. @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__input-container {
    @apply flex flex-1 items-center;
    overflow-x: auto;
    overflow-y: clip;
    scrollbar-width: none;
  }

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

DateField.Group CSS 클래스 (CSS Classes)

  • .date-input-group – 루트 컨테이너 스타일링
  • .date-input-group__input – 입력 래퍼 스타일링
  • .date-input-group__input-container – 여러 입력을 그룹화하는 스크롤 가능한 컨테이너
  • .date-input-group__segment – 개별 날짜 세그먼트 스타일링
  • .date-input-group__prefix – 접두사 요소 스타일링
  • .date-input-group__suffix – 접미사 요소 스타일링

DateField.Group 인터랙티브 상태 (Interactive States)

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

더 알아보기 (Learn more)