Field
Field (폼 필드)
폼 컨트롤에 라벨링과 검증(validation)을 제공하는 컴포넌트예요. 폼 필드에 라벨, 에러, 설명, 유효성 상태를 한 번에 연결할 수 있는 고품질의 비스타일(unstyled) React 필드 컴포넌트예요.
출처: Base UI Field
본문
폼 컨트롤에 라벨링과 검증을 제공하는 고품질의 비스타일 React 필드 컴포넌트예요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import { Field } from '@base-ui/react/field';
export default function ExampleField() {
return (
<Field.Root className="flex w-full max-w-64 flex-col items-start gap-1">
<Field.Label className="text-sm font-bold text-neutral-950 dark:text-white">Name</Field.Label>
<Field.Control
required
placeholder="Required"
className="h-8 self-stretch border border-neutral-950 bg-white dark:bg-neutral-950 px-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 placeholder:text-neutral-500 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white dark:placeholder:text-neutral-400"
/>
<Field.Error className="text-sm text-red-700 dark:text-red-400" match="valueMissing">
Please enter your name
</Field.Error>
<Field.Description className="text-sm text-neutral-600 dark:text-neutral-400">
Visible on your profile
</Field.Description>
</Field.Root>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 16rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Input {
box-sizing: border-box;
padding: 0 0.5rem;
margin: 0;
border-radius: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 100%;
height: 2rem;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Error {
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(50.5% 0.213 27.518deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.4% 0.191 22.216deg);
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
/* index.tsx */
import { Field } from '@base-ui/react/field';
import styles from './index.module.css';
export default function ExampleField() {
return (
<Field.Root className={styles.Field}>
<Field.Label className={styles.Label}>Name</Field.Label>
<Field.Control required placeholder="Required" className={styles.Input} />
<Field.Error className={styles.Error} match="valueMissing">
Please enter your name
</Field.Error>
<Field.Description className={styles.Description}>Visible on your profile</Field.Description>
</Field.Root>
);
}
애너토미 (Anatomy)
컴포넌트를 임포트하고 파트를 조립해요.
import { Field } from '@base-ui/react/field';
<Field.Root>
<Field.Label />
<Field.Control />
<Field.Description />
<Field.Item />
<Field.Error />
<Field.Validity />
</Field.Root>;
API 레퍼런스 (API reference)
Root
필드의 모든 파트를 그룹화해요.
<div> 요소를 렌더링해요.
Root Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| name | string |
- | Identifies the field when a form is submitted.
Takes precedence over the name prop on the <Field.Control> component. |
| actionsRef | React.RefObject<Field.Root.Actions | null> |
- | A ref to imperative actions. validate: Validates the field when called. |
| dirty | boolean |
- | Whether the field's value has been changed from its initial value. Useful when the field state is controlled by an external library. |
| touched | boolean |
- | Whether the field has been touched. Useful when the field state is controlled by an external library. |
| disabled | boolean |
false |
Whether the component should ignore user interaction.
Takes precedence over the disabled prop on the <Field.Control> component. |
| invalid | boolean |
- | Whether the field is invalid. Useful when the field state is controlled by an external library. |
| validate | ((value: unknown, formValues: Form.Values) => string | void | string[] | Promise<string | void | string[] | null> | null) |
- | A function for custom validation. Return a string or an array of strings with
the error message(s) if the value is invalid. Returning nothing, null, an empty
string, or an empty array means the value is valid.
Asynchronous functions are supported, but they do not prevent form submission
when using validationMode="onSubmit". |
| validationMode | Form.ValidationMode |
'onSubmit' |
Determines when the field should be validated.
This takes precedence over the validationMode prop on <Form>. onSubmit: triggers validation when the form is submitted, and re-validates on change after submission.onBlur: triggers validation when the control loses focus.onChange: triggers validation on every change to the control value. |
| validationDebounceTime | number |
0 |
How long to wait between validate callbacks if
validationMode="onChange" is used. Specified in milliseconds. |
| className | string | ((state: Field.Root.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Root.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Root.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Root Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is valid. |
| data-invalid | - | Present when the field is invalid. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
Root.Props
Root props의 re-export예요.
Root.State
type FieldRootState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Root.Actions
type FieldRootActions = { validate: () => void };
Item
체크박스 그룹이나 라디오 그룹의 개별 항목을 라벨과 설명과 함께 그룹화해요.
<div> 요소를 렌더링해요.
Item Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean |
false |
Whether the wrapped control should ignore user interaction.
The disabled prop on <Field.Root> takes precedence over this. |
| className | string | ((state: Field.Item.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Item.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Item.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Item Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is in a valid state. |
| data-invalid | - | Present when the field is in an invalid state. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
Item.Props
Item props의 re-export예요.
Item.State
type FieldItemState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Description
필드에 대한 추가 정보를 담은 문단이에요.
<p> 요소를 렌더링해요.
Description Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| className | string | ((state: Field.Description.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Description.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Description.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Description Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is in a valid state. |
| data-invalid | - | Present when the field is in an invalid state. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
Description.Props
Description props의 re-export예요.
Description.State
type FieldDescriptionState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Control
라벨링하고 검증할 폼 컨트롤이에요.
<input> 요소를 렌더링해요.
이 파트를 생략하고 어떤 Base UI 입력 컴포넌트든 대신 쓸 수 있어요. 예를 들어, Input, Checkbox, Select 등이 Field와 바로 동작해요.
Control Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| defaultValue | string | number | string[] |
- | - |
| onValueChange | ((value: string, eventDetails: Field.Control.ChangeEventDetails) => void) |
- | Callback fired when the value changes. Use when controlled. |
| className | string | ((state: Field.Control.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Control.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Control.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Control Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is in a valid state. |
| data-invalid | - | Present when the field is in an invalid state. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
Control.Props
Control props의 re-export예요.
Control.State
type FieldControlState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Control.ChangeEventReason
type FieldControlChangeEventReason = 'none';
Control.ChangeEventDetails
type FieldControlChangeEventDetails = {
/** The reason for the event. */
reason: 'none';
/** The native event associated with the custom event. */
event: Event;
/** Cancels Base UI from handling the event. */
cancel: () => void;
/** Allows the event to propagate in cases where Base UI will stop the propagation. */
allowPropagation: () => void;
/** Indicates whether the event has been canceled. */
isCanceled: boolean;
/** Indicates whether the event is allowed to propagate. */
isPropagationAllowed: boolean;
/** The element that triggered the event, if applicable. */
trigger: Element | undefined;
};
Label
폼 컨트롤에 자동으로 연결되는 접근성 좋은 라벨이에요.
<label> 요소를 렌더링해요.
Label Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| nativeLabel | boolean |
true |
Whether the component renders a native <label> element when replacing it via the render prop.
Set to false if the rendered element is not a label (for example, <div>). This is useful to avoid inheriting label behaviors on <button> controls (such as <Select.Trigger> and <Combobox.Trigger>), including avoiding :hover on the button when hovering the label, and preventing clicks on the label from firing on the button. |
| className | string | ((state: Field.Label.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Label.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Label.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Label Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is in a valid state. |
| data-invalid | - | Present when the field is in an invalid state. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
Label.Props
Label props의 re-export예요.
Label.State
type FieldLabelState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Error
필드 컨트롤이 검증에 실패했을 때 표시되는 에러 메시지예요.
<div> 요소를 렌더링해요.
Error Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| match | boolean | 'valid' | 'badInput' | 'customError' | 'patternMismatch' | 'rangeOverflow' | 'rangeUnderflow' | 'stepMismatch' | 'tooLong' | 'tooShort' | 'typeMismatch' | 'valueMissing' |
- | Determines whether to show the error message according to the field's
ValidityState.
Specifying true will always show the error message, and lets external libraries
control the visibility. |
| className | string | ((state: Field.Error.State) => string | undefined) |
- | CSS class applied to the element, or a function that returns a class based on the component's state. |
| style | React.CSSProperties | ((state: Field.Error.State) => React.CSSProperties | undefined) |
- | Style applied to the element, or a function that returns a style object based on the component's state. |
| render | ReactElement | ((props: HTMLProps, state: Field.Error.State) => ReactElement) |
- | Allows you to replace the component's HTML element
with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render. |
Error Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | Present when the field is disabled. |
| data-valid | - | Present when the field is in a valid state. |
| data-invalid | - | Present when the field is in an invalid state. |
| data-dirty | - | Present when the field's value has changed. |
| data-touched | - | Present when the field has been touched. |
| data-filled | - | Present when the field is filled. |
| data-focused | - | Present when the field control is focused. |
| data-starting-style | - | Present when the error message begins animating in. |
| data-ending-style | - | Present when the error message is animating out. |
Error.Props
Error props의 re-export예요.
Error.State
type FieldErrorState = {
/** The transition status of the component. */
transitionStatus: TransitionStatus;
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Validity
필드의 유효성 상태에 기반한 커스텀 메시지를 표시하는 데 써요.
children은 필드 유효성 상태를 인자로 받는 함수여야 해요.
Validity Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| children* | ((state: Field.Validity.State) => React.ReactNode) |
- | A function that accepts the field validity state as an argument. |
Validity.Props
Validity props의 re-export예요.
Validity.State
type FieldValidityState = {
/** The validity state. */
validity: {
badInput: boolean;
customError: boolean;
patternMismatch: boolean;
rangeOverflow: boolean;
rangeUnderflow: boolean;
stepMismatch: boolean;
tooLong: boolean;
tooShort: boolean;
typeMismatch: boolean;
valueMissing: boolean;
valid: boolean | null;
};
/** The transition status of the component. */
transitionStatus: TransitionStatus;
errors: string[];
value: unknown;
error: string;
initialValue: unknown;
};
추가 타입 (Additional Types)
Field.ValidityData
type FieldValidityData = {
state: {
badInput: boolean;
customError: boolean;
patternMismatch: boolean;
rangeOverflow: boolean;
rangeUnderflow: boolean;
stepMismatch: boolean;
tooLong: boolean;
tooShort: boolean;
typeMismatch: boolean;
valueMissing: boolean;
valid: boolean | null;
};
error: string;
errors: string[];
value: unknown;
initialValue: unknown;
};
외부 타입 (External Types)
ValidationMode
type ValidationMode = 'onSubmit' | 'onBlur' | 'onChange';
내보내기 그룹 (Export Groups)
Field.Root:Field.Root,Field.Root.State,Field.Root.Props,Field.Root.ActionsField.Label:Field.Label,Field.Label.State,Field.Label.PropsField.Error:Field.Error,Field.Error.State,Field.Error.PropsField.Description:Field.Description,Field.Description.State,Field.Description.PropsField.Control:Field.Control,Field.Control.State,Field.Control.Props,Field.Control.ChangeEventReason,Field.Control.ChangeEventDetailsField.Validity:Field.Validity,Field.Validity.State,Field.Validity.PropsField.Item:Field.Item,Field.Item.State,Field.Item.PropsDefault:Field.ValidityData,FieldValidityData,FieldRootActions,FieldRootState,FieldRootProps,FieldLabelState,FieldLabelProps,FieldDescriptionState,FieldDescriptionProps,FieldErrorState,FieldErrorProps,FieldControlState,FieldControlProps,FieldControlChangeEventReason,FieldControlChangeEventDetails,FieldValidityState,FieldValidityProps,FieldItemState,FieldItemProps
Canonical Types
Canonical: Alias 매핑 — 네임스페이스가 이미 임포트되어 있다면 Canonical을, 그렇지 않으면 Alias를 사용하세요.
Field.Root.State:FieldRootStateField.Root.Props:FieldRootPropsField.Root.Actions:FieldRootActionsField.Label.State:FieldLabelStateField.Label.Props:FieldLabelPropsField.Error.State:FieldErrorStateField.Error.Props:FieldErrorPropsField.Description.State:FieldDescriptionStateField.Description.Props:FieldDescriptionPropsField.Control.State:FieldControlStateField.Control.Props:FieldControlPropsField.Control.ChangeEventReason:FieldControlChangeEventReasonField.Control.ChangeEventDetails:FieldControlChangeEventDetailsField.Validity.State:FieldValidityStateField.Validity.Props:FieldValidityPropsField.Item.State:FieldItemStateField.Item.Props:FieldItemPropsField.ValidityData:FieldValidityData