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

Date Field 문서

원문 보기 위키 갱신

Date Field는 네이티브 <input type="date"> 요소의 대안으로, 지정된 필드 안에서 날짜를 더 유연하고 커스터마이즈 가능한 방식으로 선택할 수 있게 해 주는 컴포넌트예요.

출처: 문서

본문

아래 예시에서는 생년월일 입력을 Date Field로 구성해요. 날짜를 연·월·일 세그먼트로 나누어 보여 주고, 각 세그먼트를 개별적으로 편집할 수 있게 만들었어요.

<script lang="ts">
  import { DateField } from "bits-ui";
</script>
<DateField.Root>
  <div class="flex w-full max-w-[280px] flex-col gap-1.5">
    <DateField.Label class="block select-none text-sm font-medium"
      >Birthday</DateField.Label
    >
    <DateField.Input
      class="h-input rounded-input border-border-input bg-background text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-invalid:border-destructive flex w-full select-none items-center border px-2 py-3 text-sm tracking-[0.01em] "
    >
      {#snippet children({ segments })}
        {#each segments as { part, value }, i (part + i)}
          <div class="inline-block select-none">
            {#if part === "literal"}
              <DateField.Segment {part} class="text-muted-foreground p-1">
                {value}
              </DateField.Segment>
            {:else}
              <DateField.Segment
                {part}
                class="rounded-5px hover:bg-muted focus:bg-muted focus:text-foreground aria-[valuetext=Empty]:text-muted-foreground data-invalid:text-destructive focus-visible:ring-0! focus-visible:ring-offset-0! px-1 py-1"
              >
                {value}
              </DateField.Segment>
            {/if}
          </div>
        {/each}
      {/snippet}
    </DateField.Input>
  </div>
</DateField.Root>
참고하세요!

이 컴포넌트를 다루기 전에 Bits UI에서 날짜/시간이 어떻게 동작하는지 이해하는 게 중요해요. 자세한 내용은 Dates 문서를 꼭 읽어 보세요!

개요 (Overview)

DateField 컴포넌트는 네이티브 <input type="date"> 요소의 대안이에요. 지정된 필드 안에서 날짜를 선택하는 더 유연하고 커스터마이즈 가능한 방법을 제공해요.

구조 (Structure)

기본 구조는 Root 안에 Label과 Input을 두고, 그 안에서 각 세그먼트를 순회하며 렌더링해요.

<script lang="ts">
  import { DateField } from "bits-ui";
</script>
<DateField.Root>
  <DateField.Label>Check-in date</DateField.Label>
  <DateField.Input>
    {#snippet children({ segments })}
      {#each segments as { part, value }}
        <DateField.Segment {part}>
          {value}
        </DateField.Segment>
      {/each}
    {/snippet}
  </DateField.Input>
</DateField.Root>

재사용 컴포넌트 (Reusable Components)

DateField 프리미티브로 애플리케이션 곳곳에서 쓸 수 있는 나만의 날짜 필드 컴포넌트를 만드는 걸 권장해요.

다음 예시는 애플리케이션 전반에서 재사용할 수 있는 MyDateField 컴포넌트를 만드는 방법을 보여 줘요. 스타일 참고는 이 페이지 맨 위의 데모를 살펴보세요.

MyDateField.svelte

<script lang="ts">
  import { DateField, type WithoutChildrenOrChild } from "bits-ui";
  let {
    value = $bindable(),
    placeholder = $bindable(),
    name,
    ...restProps
  }: WithoutChildrenOrChild<DateField.RootProps> & {
    labelText: string;
    name?: string;
  } = $props();
</script>
<DateField.Root bind:value bind:placeholder {...restProps}>
  <DateField.Label {name}>{labelText}</DateField.Label>
  <DateField.Input>
    {#snippet children({ segments })}
      {#each segments as { part, value }}
        <DateField.Segment {part}>
          {value}
        </DateField.Segment>
      {/each}
    {/snippet}
  </DateField.Input>
</DateField.Root>

Expand Code

<script lang="ts">
  import { DateField } from "bits-ui";
  let {
    labelText = "Select a date",
    value = $bindable(),
    placeholder = $bindable(),
    name,
    ...restProps
  }: DateField.RootProps & { labelText: string; name?: string } = $props();
</script>
<DateField.Root bind:value bind:placeholder {...restProps}>
  <div class="flex w-fit min-w-[280px] flex-col gap-1.5">
    <DateField.Label class="block select-none text-sm font-medium"
      >{labelText}</DateField.Label
    >
    <DateField.Input
      {name}
      class="h-input rounded-input border-border-input bg-background text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-invalid:border-destructive flex w-full select-none items-center border px-2 py-3 text-sm tracking-[0.01em] "
    >
      {#snippet children({ segments })}
        {#each segments as { part, value }, i (part + i)}
          <div class="inline-block select-none">
            {#if part === "literal"}
              <DateField.Segment {part} class="text-muted-foreground p-1">
                {value}
              </DateField.Segment>
            {:else}
              <DateField.Segment
                {part}
                class="rounded-5px hover:bg-muted focus:bg-muted focus:text-foreground aria-[valuetext=Empty]:text-muted-foreground data-invalid:text-destructive focus-visible:ring-0! focus-visible:ring-offset-0! px-1 py-1"
              >
                {value}
              </DateField.Segment>
            {/if}
          </div>
        {/each}
      {/snippet}
    </DateField.Input>
  </div>
</DateField.Root>

이어지는 데모와 예시에서는 같은 코드를 반복하지 않도록 새로 만든 MyDateField 컴포넌트를 사용할게요. 문서를 읽어 가면서 잘 참고해 주세요.

세그먼트 (Segments)

DateField의 세그먼트는 날짜의 특정 부분(일, 월, 연, 시)을 나타낼 뿐 아니라, 날짜의 서로 다른 부분 사이를 구분하는 "literal"을 가리킬 수도 있어요. "literal"은 보통 구분 기호 역할을 하며 locale에 따라 달라져요.

아까 만든 MyDateField 컴포넌트에서 DateField.Segment를 "literal"인지 아닌지에 따라 다르게 스타일링하고 있는 걸 눈여겨보세요.

플레이스홀더 (Placeholder)

DateField.Root 컴포넌트의 placeholder prop은 필드가 비어 있을 때 보여 주는 값이 아니에요. 사용자가 세그먼트를 순회하며 바꾸려고 할 때 필드가 어떤 날짜에서 시작해야 하는지를 나타내는 값이죠. 플레이스홀더는 날짜 필드의 granularity를 정하는 데도 쓰이며, 이에 따라 value에 사용되는 DateValue 객체 타입이 결정돼요.

기본적으로 placeholder는 현재 날짜에서 가장 가까운 허용값(maxValue, minValue로 제한됨)으로 설정되고 CalendarDate 타입이 돼요. 하지만 시간 선택도 지원하고 싶다면 플레이스홀더를 CalendarDateTime 객체로 설정할 수 있어요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { CalendarDateTime } from "@internationalized/date";
</script>
<MyDateField placeholder={new CalendarDateTime(2024, 8, 3, 12, 30)} />

사용자에게 시간대까지 함께 수집해야 한다면 대신 ZonedDateTime 객체를 사용할 수 있어요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { now, getLocalTimeZone } from "@internationalized/date";
</script>
<MyDateField placeholder={now("America/New_York")} />
윤년 (Leap Years)!

생일 같은 날짜 필드를 만들고 있다면 플레이스홀더를 윤년으로 설정해야 해요. 그래야 윤년에 태어난 사용자도 올바른 날짜를 선택할 수 있어요.

플레이스홀더 상태 관리 (Managing Placeholder State)

이번엔 Date Field의 placeholder 상태를 관리하는 방법을 알아볼게요.

양방향 바인딩 (Two-Way Binding)

간단하고 자동적인 상태 동기화는 bind:placeholder로 처리해요.

<script lang="ts">
  import { DateField } from "bits-ui";
  import { CalendarDateTime } from "@internationalized/date";
  let myPlaceholder = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<button onclick={() => (myPlaceholder = new CalendarDate(2024, 8, 3))}>
  Set placeholder to August 3rd, 2024
</button>
<DateField.Root bind:placeholder={myPlaceholder}>
  <!-- ... -->
</DateField.Root>

완전 제어 (Fully Controlled)

상태의 읽기와 쓰기를 전부 제어하고 싶다면 Function Binding을 사용해요.

<script lang="ts">
  import { DateField } from "bits-ui";
  import type { DateValue } from "@internationalized/date";
  let myPlaceholder = $state<DateValue>();
  function getPlaceholder() {
    return myPlaceholder;
  }
  function setPlaceholder(newPlaceholder: DateValue) {
    myPlaceholder = newPlaceholder;
  }
</script>
<DateField.Root bind:placeholder={getPlaceholder, setPlaceholder}>
  <!-- ... -->
</DateField.Root>

값 상태 관리 (Managing Value State)

이번엔 Date Field의 value 상태를 관리하는 방법을 알아볼게요.

양방향 바인딩 (Two-Way Binding)

간단하고 자동적인 상태 동기화는 bind:value로 처리해요.

<script lang="ts">
  import { DateField } from "bits-ui";
  import { CalendarDateTime } from "@internationalized/date";
  let myValue = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<button onclick={() => (myValue = myValue.add({ days: 1 }))}>
  Add 1 day
</button>
<DateField.Root bind:value={myValue}>
  <!-- ... -->
</DateField.Root>

완전 제어 (Fully Controlled)

컴포넌트의 상태를 완전히 제어하려면 Function Binding으로 값 상태를 외부에서 관리해요.

<script lang="ts">
  import { DateField } from "bits-ui";
  import type { DateValue } from "@internationalized/date";
  let myValue = $state<DateValue>();
  function getValue() {
    return myValue;
  }
  function setValue(newValue: DateValue | undefined) {
    myValue = newValue;
  }
</script>
<DateField.Root bind:value={getValue, setValue}>
  <!-- ... -->
</DateField.Root>

기본값 (Default Value)

DateField.Root 컴포넌트를 기본값으로 시작하고 싶은 경우가 많아요. 이런 값은 보통 데이터베이스에서 ISO 8601 문자열 형태로 온답니다. @internationalized/date 패키지의 parseDate 함수로 문자열을 CalendarDate 객체로 변환할 수 있어요.

+page.svelte

<script lang="ts">
  import { DateField } from "bits-ui";
  import { parseDate } from "@internationalized/date";
  // this came from a database/API call
  const date = "2024-08-03";
  let value = $state(parseDate(date));
</script>
<DateField.Root {value}>
  <!-- ... -->
</DateField.Root>

이제 입력에 기본값이 채워져요. parseDate 외에도 parseDateTime이나 parseZonedDateTime으로 문자열을 각각 CalendarDateTime 또는 ZonedDateTime 객체로 변환할 수 있어요.

검증 (Validation)

최소값 (Minimum Value)

DateField.Root 컴포넌트의 최소값은 minValue prop으로 설정해요. 사용자가 최소값보다 작은 날짜를 선택하면 날짜 필드가 유효하지 않음으로 표시돼요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { today, getLocalTimeZone } from "@internationalized/date";
  const todayDate = today(getLocalTimeZone());
  const yesterday = todayDate.subtract({ days: 1 });
</script>
<MyDateField minValue={todayDate} value={yesterday} />

위 예시는 최소값을 오늘로, 기본값을 어제로 설정했어요. 그래서 날짜 필드가 유효하지 않음으로 표시되고, 이에 맞게 스타일링할 수 있어요. 날짜를 최소값보다 크게 조정하면 유효하지 않음 상태는 사라져요.

최대값 (Maximum Value)

DateField.Root 컴포넌트의 최대값은 maxValue prop으로 설정해요. 사용자가 최대값보다 큰 날짜를 선택하면 날짜 필드가 유효하지 않음으로 표시돼요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { today, getLocalTimeZone } from "@internationalized/date";
  const todayDate = today(getLocalTimeZone());
  const tomorrow = todayDate.add({ days: 1 });
</script>
<MyDateField maxValue={todayDate} value={tomorrow} />

위 예시는 최대값을 오늘로, 기본값을 내일로 설정했어요. 그래서 날짜 필드가 유효하지 않음으로 표시되고, 이에 맞게 스타일링할 수 있어요. 날짜를 최대값보다 작게 조정하면 유효하지 않음 상태는 사라져요.

커스텀 검증 (Custom Validation)

validate prop으로 날짜 필드에 커스텀 검증 함수를 제공할 수 있어요. 이 함수는 날짜가 유효하지 않으면 검증 오류로 문자열이나 문자열 배열을 반환하고, 유효하다면 undefined나 아무것도 반환하지 않아야 해요.

반환된 문자열은 onInvalid 콜백으로 전달되는데, 이걸로 사용자에게 오류 메시지를 보여 줄 수 있어요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { CalendarDate, type DateValue } from "@internationalized/date";
  const value = new CalendarDate(2024, 8, 2);
  function validate(date: DateValue) {
    return date.day === 1
      ? "Date cannot be the first day of the month"
      : undefined;
  }
  function onInvalid(
    reason: "min" | "max" | "custom",
    msg?: string | string[]
  ) {
    if (reason === "custom") {
      if (typeof msg === "string") {
        // do something with the error message
        console.log(msg);
        return;
      } else if (Array.isArray(msg)) {
        // do something with the error messages
        console.log(msg);
        return;
      }
      console.log("The date is invalid");
    } else if (reason === "min") {
      // let the user know that the date is too early.
      console.log("The date is too early.");
    } else if (reason === "max") {
      // let the user know that the date is too late.
      console.log("The date is too late.");
    }
  }
</script>
<MyDateField {validate} {value} {onInvalid} />

그 달의 1일을 선택해 보면 날짜 필드가 유효하지 않음으로 표시되는 걸 확인할 수 있어요.

Granularity

granularity prop은 날짜 필드의 정밀도를 설정해서, 어떤 세그먼트가 렌더링될지를 결정해요. granularity는 'day', 'hour', 'minute', 'second' 중 하나로 설정할 수 있어요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
  import { CalendarDateTime } from "@internationalized/date";
  const value = new CalendarDateTime(2024, 8, 2, 12, 30);
</script>
<MyDateField granularity="second" {value} />

위 예시는 granularity를 'second'로 설정해서, 날짜 필드에 초 세그먼트가 추가로 포함되는 걸 볼 수 있어요.

현지화 (Localization)

locale prop으로 날짜 필드의 로케일을 설정할 수 있어요. 이는 날짜 필드의 세그먼트와 플레이스홀더 형식에 영향을 줘요.

<script lang="ts">
  import MyDateField from "$lib/components/MyDateField.svelte";
</script>
<MyDateField locale="de" />

API Reference

DateField.Root

The root date field component.

Property Type Description Details
value DateValue - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate | CalendarDateTime | ZonedDateTime The selected date.Default: —— undefined
onValueChange function - (date: DateValue) => void A function that is called when the date value changes.Default: —— undefined
placeholder $bindable DateValue - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate | CalendarDateTime | ZonedDateTime The placeholder date, which is used to determine what date to start the segments from when no value exists.Default: —— undefined
onPlaceholderChange function - (date: DateValue) => void A function that is called when the placeholder date changes.Default: —— undefined
required boolean Whether or not the date field is required.Default: false
validate function - (date: DateValue) => string[] | string | void A function that returns whether or not a date is valid.Default: —— undefined
onInvalid function - (reason: 'min' | 'max' | 'custom', msg?: string | string[]) => void A callback fired when the value is invalid.Default: —— undefined
errorMessageId string The id of the element which contains the error messages for the date field when the date is invalid.Default: —— undefined
hourCycle enum - '12' | '24' The hour cycle to use for formatting times. Defaults to the locale preferenceDefault: —— undefined
granularity enum - 'day' | 'hour' | 'minute' | 'second' The granularity to use for formatting the field. Defaults to 'day' if a CalendarDate is provided, otherwise defaults to 'minute'. The field will render segments for each part of the date up to and including the specified granularity.Default: —— undefined
hideTimeZone boolean Whether or not to hide the time zone segment of the field.Default: false
maxValue DateValue - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate | CalendarDateTime | ZonedDateTime The maximum valid date that can be entered.Default: —— undefined
minValue DateValue - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate | CalendarDateTime | ZonedDateTime The minimum valid date that can be entered.Default: —— undefined
locale string The locale to use for formatting dates.Default: en-US
disabled boolean Whether or not the field is disabled.Default: false
readonly boolean Whether or not the field is readonly.Default: false
readonlySegments EditableSegmentPart[] - "day" | "month" | "year" | "hour" | "minute" | "second" | "dayPeriod" An array of segments that should be readonly, which prevent user input on them.Default: —— undefined
children Snippet The children content to render.Default: —— undefined

DateField.Input

The container for the segments of the date field.

Property Type Description Details
name string The name of the date field used for form submission. If provided, a hidden input element will be rendered alongside the date field.Default: —— undefined
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet - import type { SegmentPart } from "bits-ui" type ChildrenSnippetProps = { segments: Array<{ part: SegmentPart; value: string }> } The children content to render.Default: —— undefined
child Snippet - import type { SegmentPart } from "bits-ui" type ChildSnippetProps = { props: Record<string, unknown> segments: Array<{ part: SegmentPart; value: string }> } Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid.
data-disabled '' Present on the element when the field is disabled.
data-date-field-input '' Present on the element.

DateField.Segment

A segment of the date field.

Property Type Description Details
part required SegmentPart - "day" |"month" | "year" | "hour" | "minute" | "second" | "dayPeriod" | "timeZoneName" | "literal"; The part of the date to render.Default: —— undefined
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default: —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid
data-disabled '' Present on the element when the field is disabled
data-readonly '' Present on the element when the field or segment is readonly
data-segment enum - 'day' | 'month' | 'year' | 'hour' | 'minute' | 'second' | 'dayPeriod' | 'timeZoneName' | 'literal' The part of the date being rendered.
data-date-field-segment '' Present on the element.

DateField.Label

The label for the date field.

Property Type Description Details
ref $bindable HTMLSpanElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default: —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid
data-disabled '' Present on the element when the field is disabled
data-date-field-label '' Present on the element.

더 알아보기 (Learn more)

Date Field는 단일 날짜를 입력받을 때 쓰는 컴포넌트예요. 날짜 범위가 필요하면 두 개의 Date Field를 합친 Date Range Field를, 캘린더 팝업에서 선택하고 싶다면 Date Picker를 살펴보세요. 이 컴포넌트들이 서로를 어떻게 보완하는지 알아 두면 날짜 입력 UI를 설계할 때 선택지가 넓어져요.