Form (폼)
Form은 폼 검증과 제출 처리를 위한 래퍼 컴포넌트예요. 해요체로 쉽게 설명드릴게요.
출처: HeroUI Form
본문
사용법 (Usage)
import { Form } from '@heroui/react';
{"name": "form-basic"}
구조 (Anatomy)
import {Form, Button} from '@heroui/react';
export default () => (
<Form>
{/* Form fields go here */}
<Button type="submit"/>
<Button type="reset"/>
</Form>
)
예시 (Examples)
렌더 함수 (Render Function)
{"name": "form-render-function"}
커스터마이징 (Customization)
Tailwind CSS
{"name": "form-custom-styles"}
Global CSS
폼 레이아웃과 간격을 커스터마이징하려면 <Form>의 className prop을 사용하거나 @layer components 지시어로 프로젝트 수준의 클래스를 추가해요.
더 알아보기.
Form은 네이티브 <form> 요소를 렌더링하며 검증과 제출에 집중해요. @heroui/styles에는 전용 BEM 클래스가 포함되어 있지 않아요. 컨테이너 스타일은 전역 CSS에서 적용하고, 컨트롤 수준의 커스터마이징은 필드 컴포넌트를 사용해요.
@layer components {
.form-layout {
@apply flex flex-col gap-4 rounded-xl border border-border bg-surface p-4 shadow-sm;
}
}
<Form className="form-layout" onSubmit={handleSubmit}>
{/* TextField, Input, Button, etc. */}
</Form>
공유 레이아웃의 그룹 필드에는 Fieldset을 사용하고 .fieldset, .fieldset__legend 및 관련 클래스를 대상으로 해요. 개별 컨트롤은 TextField, Input, Label, FieldError의 Global CSS를 참고해요.
스타일링 참고 (Styling Reference)
HeroUI는 @heroui/styles에서 스타일을 제공하는 컴포넌트에 대해 BEM 방법론을 따라요.
Form은 전용 BEM 클래스 없이 네이티브 <form> 요소를 렌더링해요. 레이아웃, 간격, 서페이스 스타일은 className으로 적용해요. 필드 모양과 검증 상태는 TextField, Input, Label, Description, FieldError 같은 자식 컴포넌트에서 온답니다. 구조화된 다중 필드 레이아웃은 Fieldset으로 구성해요.
API 참고 (API Reference)
Form
Form 컴포넌트는 폼 검증과 제출 처리를 제공하는 React Aria의 Form 프리미티브 래퍼예요.
| Prop | Type | Default | Description |
|---|---|---|---|
action |
string | FormHTMLAttributes['action'] |
- | The URL to submit the form data to. |
className |
string |
- | Tailwind CSS classes applied to the form element. |
children |
React.ReactNode |
- | Form content (fields, buttons, etc.). |
encType |
'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain' |
- | The encoding type for form data submission. |
method |
'get' | 'post' |
- | The HTTP method to use when submitting the form. |
onInvalid |
(event: FormEvent<HTMLFormElement>) => void |
- | Handler called when the form validation fails. By default, the first invalid field will be focused. Use preventDefault() to customize focus behavior. |
onReset |
(event: FormEvent<HTMLFormElement>) => void |
- | Handler called when the form is reset. |
onSubmit |
(event: FormEvent<HTMLFormElement>) => void |
- | Handler called when the form is submitted. |
target |
'_self' | '_blank' | '_parent' | '_top' |
- | Where to display the response after submitting the form. |
validationBehavior |
'native' | 'aria' |
'native' |
Whether to use native HTML validation or ARIA validation. 'native' blocks form submission, 'aria' displays errors in realtime. |
validationErrors |
ValidationErrors |
- | Server-side validation errors mapped by field name. Displayed immediately and cleared when user modifies the field. |
aria-label |
string |
- | Accessibility label for the form. |
aria-labelledby |
string |
- | ID of element that labels the form. Creates a form landmark when provided. |
render |
DOMRenderFunction<keyof React.JSX.IntrinsicElements, undefined> |
- | Overrides the default DOM element with a custom render function. |
폼 검증 (Form Validation)
Form 컴포넌트는 React Aria의 검증 시스템과 통합되어 다음을 할 수 있어요:
- 내장된 HTML5 검증 속성(
required,minLength,pattern등) 사용 - TextField 컴포넌트에 커스텀 검증 함수 제공
- FieldError 컴포넌트로 검증 오류 표시
- 적절한 검증과 함께 폼 제출 처리
validationErrorsprop으로 서버 측 검증 오류 제공
검증 동작 (Validation Behavior)
validationBehavior prop은 검증이 표시되는 방식을 제어해요:
native(기본값): 네이티브 HTML 검증 사용, 오류 발생 시 폼 제출 차단aria: 검증에 ARIA 속성 사용, 사용자가 입력하는 동안 실시간으로 오류 표시, 제출은 차단하지 않음
이 동작은 폼 수준에서 설정하거나 개별 필드 수준에서 재정의할 수 있어요.
폼 제출 (Form Submission)
폼은 여러 가지 방법으로 제출할 수 있어요:
- 전통적인 제출:
actionprop을 설정해 URL로 제출 - JavaScript 처리:
onSubmit핸들러로 폼 데이터 처리 - FormData API: 제출 핸들러에서 FormData API로 폼 데이터 접근
FormData 예시:
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const data = Object.fromEntries(formData);
console.log('Form data:', data);
}
폼 필드와의 통합 (Integration with Form Fields)
Form 컴포넌트는 HeroUI의 폼 필드 컴포넌트와 원활하게 동작해요:
- TextField: 라벨과 검증이 있는 텍스트 입력
- Checkbox: 불리언 선택
- RadioGroup: 여러 옵션 중 단일 선택
- Switch: 토글 컨트롤
- Button: 폼 제출과 리셋 동작
모든 필드 컴포넌트는 Form 안에 배치되면 자동으로 Form의 검증 및 제출 동작과 통합돼요.
고급 사용법 (Advanced Usage)
다음과 같은 고급 사용 사례의 경우:
- 커스텀 검증 컨텍스트
- Form 컨텍스트 프로바이더
- 서드파티 라이브러리 통합
- 검증 오류 시 커스텀 포커스 관리
React Aria Form 문서를 참고해요.
접근성 (Accessibility)
React Aria 컴포넌트를 사용하면 폼은 기본적으로 접근성을 지원해요. 주요 기능은 다음과 같아요:
- 네이티브
<form>요소 의미론 aria-label또는aria-labelledby로 폼 랜드마크 생성- 검증 오류 시 자동 포커스 관리
validationBehavior="aria"사용 시 ARIA 검증 속성
더 알아보기 (Learn more)
- React Aria Form 문서 - 폼 컴포넌트
- Fieldset - 그룹 필드 레이아웃