Form actions
Form actions
폼 상태를 애플리케이션 어디에서나 변경할 수 있게 해주는 createFormActions를 다루는 문서예요. useForm 설정에서 지정한 것과 같은 폼 이름으로 createFormActions 함수를 호출해요.
출처: 문서
본문
useForm을 정의한 파일에서 폼 값의 타입을 임포트하고, useForm 설정에서 지정한 것과 같은 폼 이름으로 createFormActions 함수를 호출해요.
// useForm을 정의한 파일에서 폼 값의 타입을 임포트해요
import { createFormActions } from '@mantine/form';
import type { DemoFormValues } from './DemoForm';
export const demoFormActions =
createFormActions('demo-form');
그 후 애플리케이션 어디에서나 demoFormActions를 사용해 폼 상태를 변경할 수 있어요. 예를 들어 fetch 요청 후 또는 폼 상태에 접근할 수 없는 컴포넌트와의 사용자 상호작용 후에 사용할 수 있어요.
import { useEffect } from 'react';
import { Button } from '@mantine/core';
import { demoFormActions } from './demoFormActions';
function ExternalComponent() {
useEffect(() => {
fetch('/api/user')
.then((res) => res.json())
.then((res) =>
demoFormActions.setValues({
name: res.name,
age: res.age,
})
);
}, []);
return (
<Button onClick={() => demoFormActions.reset()}>
Reset demo form
</Button>
);
}
Form name
폼 이름은 문자, 숫자, 대시만 포함하는 문자열이어야 해요.
import { useForm } from '@mantine/form';
// ✅ 유효한 폼 이름
const valid = useForm({
name: 'valid-FORM-name-10',
mode: 'uncontrolled',
});
// ❌ 유효하지 않은 폼 이름: 공백과 특수 문자가 포함되면 안 돼요
const invalid = useForm({
name: 'invalid_form name',
mode: 'uncontrolled',
});
폼 이름은 고유해야 한다는 점에 주의해요. 같은 이름의 폼이 여러 개 있으면 폼 액션이 그 이름을 가진 모든 폼의 상태를 갱신해요.
Form actions
createFormActions 함수는 다음 메서드를 가진 객체를 반환해요.
setFieldValuesetValuessetInitialValuessetErrorssetFieldErrorclearFieldErrorclearErrorsresetvalidatevalidateFieldreorderListItemremoveListIteminsertListItemsetDirtysetTouchedresetDirtyresetTouched
모든 메서드는 use-form 훅 메서드와 비슷하게 동작해요. 함수는 같은 인자를 받지만 아무것도 반환하지 않아요.