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

폼

원문 보기 위키 갱신

폼 (Form)

통합된 에러 처리를 갖춘 고품질의 비스타일 React 폼 컴포넌트예요. 제출 시점·필드 단위 검증과 Zod 통합까지 지원해요.

출처: Base UI 폼

본문

통합된 에러 처리를 갖춘 고품질의 비스타일 React 폼 컴포넌트예요.

데모

Tailwind

이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';

export default function ExampleForm() {
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  return (
    <Form
      className="flex w-full max-w-64 flex-col gap-4"
      errors={errors}
      onSubmit={async (event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        const value = formData.get('url') as string;

        setLoading(true);
        const response = await submitForm(value);
        const serverErrors = {
          url: response.error,
        };

        setErrors(serverErrors);
        setLoading(false);
      }}
    >
      <Field.Root name="url" className="flex flex-col items-start gap-1">
        <Field.Label className="text-sm font-bold text-neutral-950 dark:text-white">
          Homepage
        </Field.Label>
        <Field.Control
          type="url"
          required
          defaultValue="https://example.com"
          placeholder="https://example.com"
          pattern="https?://.*"
          className="h-8 w-full 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" />
      </Field.Root>
      <Button
        disabled={loading}
        focusableWhenDisabled
        type="submit"
        className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400"
      >
        Submit
      </Button>
    </Form>
  );
}

async function submitForm(value: string) {
  // Mimic a server response
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });

  try {
    const url = new URL(value);

    if (url.hostname.endsWith('example.com')) {
      return { error: 'The example domain is not allowed' };
    }
  } catch {
    return { error: 'This is not a valid URL' };
  }

  return { success: true };
}

CSS Modules

이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.module.css */
.Form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 100%;
  max-width: 16rem;
}

.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
}

.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);
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  outline: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';
import styles from './index.module.css';

export default function ExampleForm() {
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  return (
    <Form
      className={styles.Form}
      errors={errors}
      onSubmit={async (event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        const value = formData.get('url') as string;

        setLoading(true);
        const response = await submitForm(value);
        const serverErrors = {
          url: response.error,
        };

        setErrors(serverErrors);
        setLoading(false);
      }}
    >
      <Field.Root name="url" className={styles.Field}>
        <Field.Label className={styles.Label}>Homepage</Field.Label>
        <Field.Control
          type="url"
          required
          defaultValue="https://example.com"
          placeholder="https://example.com"
          pattern="https?://.*"
          className={styles.Input}
        />
        <Field.Error className={styles.Error} />
      </Field.Root>
      <Button type="submit" disabled={loading} focusableWhenDisabled className={styles.Button}>
        Submit
      </Button>
    </Form>
  );
}

async function submitForm(value: string) {
  // Mimic a server response
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });

  try {
    const url = new URL(value);

    if (url.hostname.endsWith('example.com')) {
      return { error: 'The example domain is not allowed' };
    }
  } catch {
    return { error: 'This is not a valid URL' };
  }

  return { success: true };
}

구조 (Anatomy)

Form은 Field와 함께 구성돼요. 컴포넌트를 임포트하고 함께 배치해요.

import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';

<Form>
  <Field.Root>
    <Field.Label />
    <Field.Control />
    <Field.Error />
  </Field.Root>
</Form>;

예시

서버 함수로 제출하기

useActionState를 사용하는 폼은 onSubmit 대신 Server Function으로 제출할 수 있어요.

데모

Tailwind

이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';

interface FormState {
  serverErrors?: Form.Props['errors'];
}

export default function ActionStateForm() {
  const [state, formAction, loading] = React.useActionState<FormState, FormData>(submitForm, {});

  return (
    <Form
      action={formAction}
      errors={state.serverErrors}
      className="flex w-full max-w-64 flex-col gap-4"
    >
      <Field.Root name="username" className="flex flex-col items-start gap-1">
        <Field.Label className="text-sm font-bold text-neutral-950 dark:text-white">
          Username
        </Field.Label>
        <Field.Control
          type="text"
          autoComplete="username"
          required
          defaultValue="admin"
          placeholder="e.g. alice132"
          className="h-8 w-full 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" />
      </Field.Root>
      <Button
        type="submit"
        disabled={loading}
        focusableWhenDisabled
        className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400"
      >
        Submit
      </Button>
    </Form>
  );
}

// Mark this as a Server Function with `'use server'` in a supporting framework like Next.js
async function submitForm(_previousState: FormState, formData: FormData) {
  // Mimic a server response
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });

  try {
    const username = formData.get('username') as string | null;

    if (username === 'admin') {
      return { success: false, serverErrors: { username: "'admin' is reserved for system use" } };
    }

    // 50% chance the username is taken
    const success = Math.random() > 0.5;

    if (!success) {
      return {
        serverErrors: { username: `${username} is unavailable` },
      };
    }
  } catch {
    return { serverErrors: { username: 'A server error has occurred' } };
  }

  return {};
}

CSS Modules

이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.module.css */
.Form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 100%;
  max-width: 16rem;
}

.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
}

.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);
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  outline: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';
import styles from './index.module.css';

interface FormState {
  serverErrors?: Form.Props['errors'];
}

export default function ActionStateForm() {
  const [state, formAction, loading] = React.useActionState<FormState, FormData>(submitForm, {});

  return (
    <Form errors={state.serverErrors} action={formAction} className={styles.Form}>
      <Field.Root name="username" className={styles.Field}>
        <Field.Label className={styles.Label}>Username</Field.Label>
        <Field.Control
          type="text"
          autoComplete="username"
          required
          defaultValue="admin"
          placeholder="e.g. alice132"
          className={styles.Input}
        />
        <Field.Error className={styles.Error} />
      </Field.Root>
      <Button type="submit" disabled={loading} focusableWhenDisabled className={styles.Button}>
        Submit
      </Button>
    </Form>
  );
}

// Mark this as a Server Function with `'use server'` in a supporting framework like Next.js
async function submitForm(_previousState: FormState, formData: FormData) {
  // Mimic a server response
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });

  try {
    const username = formData.get('username') as string | null;

    if (username === 'admin') {
      return { success: false, serverErrors: { username: "'admin' is reserved for system use" } };
    }

    // 50% chance the username is taken
    const success = Math.random() > 0.5;

    if (!success) {
      return {
        serverErrors: { username: `${username} is unavailable` },
      };
    }
  } catch {
    return { serverErrors: { username: 'A server error has occurred' } };
  }

  return {};
}

폼 값을 JavaScript 객체로 제출하기

네이티브 onSubmit 대신 onFormSubmit을 사용하면 폼 값을 JavaScript 객체로 접근할 수 있어요. 제출 전에 값을 변환해야 하거나 제3자 API와 통합해야 할 때 유용해요.

<Form
  onFormSubmit={async (formValues: { id: string; quantity: number }) => {
    const payload = {
      product_id: formValues.id,
      order_quantity: formValues.quantity,
    };

    const response = await fetch('https://api.example.com', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
  }}
/>

사용하면 네이티브 submit 이벤트에 preventDefault가 호출돼요.

Zod와 함께 사용하기

schema.safeParse()로 스키마를 파싱할 때, z.flattenError(result.error).fieldErrors 데이터를 사용해 각 필드의 name에 에러를 매핑할 수 있어요.

데모

Tailwind

이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.tsx */
'use client';
import * as React from 'react';
import { z } from 'zod';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';

const schema = z.object({
  name: z.string().min(1, 'Name is required'),
  age: z.coerce.number('Age must be a number').positive('Age must be a positive number'),
});

async function submitForm(formValues: Form.Values) {
  const result = schema.safeParse(formValues);

  if (!result.success) {
    return {
      errors: z.flattenError(result.error).fieldErrors,
    };
  }

  return {
    errors: {},
  };
}

export default function Page() {
  const [errors, setErrors] = React.useState({});

  return (
    <Form
      className="flex w-full max-w-64 flex-col gap-4"
      errors={errors}
      onFormSubmit={async (formValues) => {
        const response = await submitForm(formValues);
        setErrors(response.errors);
      }}
    >
      <Field.Root name="name" className="flex flex-col items-start gap-1">
        <Field.Label className="text-sm font-bold text-neutral-950 dark:text-white">
          Name
        </Field.Label>
        <Field.Control
          placeholder="Enter name"
          className="h-8 w-full 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" />
      </Field.Root>
      <Field.Root name="age" className="flex flex-col items-start gap-1">
        <Field.Label className="text-sm font-bold text-neutral-950 dark:text-white">
          Age
        </Field.Label>
        <Field.Control
          placeholder="Enter age"
          className="h-8 w-full 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" />
      </Field.Root>
      <Button
        type="submit"
        className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400"
      >
        Submit
      </Button>
    </Form>
  );
}

CSS Modules

이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.module.css */
.Form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 100%;
  max-width: 16rem;
}

.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
}

.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);
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  outline: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { z } from 'zod';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { Button } from '@base-ui/react/button';
import styles from './index.module.css';

const schema = z.object({
  name: z.string().min(1, 'Name is required'),
  age: z.coerce.number('Age must be a number').positive('Age must be a positive number'),
});

async function submitForm(formValues: Form.Values) {
  const result = schema.safeParse(formValues);

  if (!result.success) {
    return {
      errors: z.flattenError(result.error).fieldErrors,
    };
  }

  return {
    errors: {},
  };
}

export default function Page() {
  const [errors, setErrors] = React.useState({});

  return (
    <Form
      className={styles.Form}
      errors={errors}
      onFormSubmit={async (formValues) => {
        const response = await submitForm(formValues);
        setErrors(response.errors);
      }}
    >
      <Field.Root name="name" className={styles.Field}>
        <Field.Label className={styles.Label}>Name</Field.Label>
        <Field.Control placeholder="Enter name" className={styles.Input} />
        <Field.Error className={styles.Error} />
      </Field.Root>
      <Field.Root name="age" className={styles.Field}>
        <Field.Label className={styles.Label}>Age</Field.Label>
        <Field.Control placeholder="Enter age" className={styles.Input} />
        <Field.Error className={styles.Error} />
      </Field.Root>
      <Button type="submit" className={styles.Button}>
        Submit
      </Button>
    </Form>
  );
}

API 레퍼런스

Form

통합된 에러 처리를 갖춘 네이티브 폼 요소예요. <form> 요소를 렌더링해요.

Form Props:

Prop Type Default Description
errors Errors - 서버나 폼 액션에 의한 제출 후 외부에서 반환된 유효성 검사 에러들. 키가 <Field.Root>의 name 속성에 대응하고, 값이 해당 필드와 관련된 에러(들)인 객체여야 해요.
actionsRef React.RefObject<Form.Actions | null> - 명령형 동작에 대한 ref. validate: 호출하면 모든 필드를 검증해요. 선택적으로 필드 이름을 전달하면 단일 필드를 검증할 수 있어요.
onFormSubmit ((formValues: Record<string, any>, eventDetails: Form.SubmitEventDetails) => void) - 폼이 제출될 때 호출되는 이벤트 핸들러. 사용하면 네이티브 submit 이벤트에 preventDefault()가 호출돼요.
validationMode Form.ValidationMode 'onSubmit' 폼을 언제 검증할지 결정해요. <Field.Root>의 validationMode prop이 이 값보다 우선해요. onSubmit (기본): 폼이 제출될 때 필드를 검증하고, 이후에는 변경 시 필드를 재검증해요.onBlur: 필드가 포커스를 잃을 때 검증해요.onChange: 값이 바뀔 때마다 필드를 검증해요.
className string | ((state: Form.State) => string | undefined) - 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태에 따라 클래스를 반환하는 함수.
style React.CSSProperties | ((state: Form.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일, 또는 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수.
render ReactElement | ((props: React.DetailedHTMLProps<React.FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>, state: Form.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요.

actionsRef Prop Example:

// validate all fields
actionsRef.current?.validate();

// validate one field
actionsRef.current?.validate('email');

Form.Props

Form props의 재내보내기예요.

Form.State

type FormState = {};

Form.Actions

type FormActions = { validate: (fieldName?: string) => void };

Form.SubmitEventDetails

type FormSubmitEventDetails = {
  /** The reason for the event. */
  reason: 'none';
  /** The native event associated with the custom event. */
  event: Event;
};

Form.SubmitEventReason

type FormSubmitEventReason = 'none';

Form.ValidationMode

type FormValidationMode = 'onSubmit' | 'onBlur' | 'onChange';

Form.Values

type FormValues = Record<string, any>;

Canonical Types

Canonical: Alias 매핑 — Canonical의 네임스페이스가 이미 임포트되어 있으면 Canonical을, 아니면 Alias를 사용하세요.

  • Form.Props: FormProps
  • Form.State: FormState
  • Form.Actions: FormActions
  • Form.ValidationMode: FormValidationMode
  • Form.SubmitEventReason: FormSubmitEventReason
  • Form.SubmitEventDetails: FormSubmitEventDetails

더 알아보기 (Learn more)