getInputProps
getInputProps
form.getInputProps를 사용해 입력에 props를 자동으로 전달하는 방법과 enhanceGetInputProps로 이를 확장하는 방법을 다루는 문서예요.
출처: 문서
본문
enhanceGetInputProps를 사용해 form.getInputProps에 전달된 옵션을 기반으로 입력에 추가 props를 더하는 예시:
import { NumberInput, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
interface FormValues {
name: string;
age: number | string;
}
function Demo() {
const form = useForm({
mode: 'uncontrolled',
initialValues: { name: '', age: '' },
enhanceGetInputProps: (payload) => {
if (payload.options.fieldType === 'name') {
return {
label: 'Your name',
placeholder: 'Your name',
withAsterisk: true,
description: 'Your personal information is stored securely. (Just kidding!)',
};
}
return {};
},
});
return (
<>
<TextInput {...form.getInputProps('name', { fieldType: 'name' })} />
<NumberInput {...form.getInputProps('age')} label="Age" />
</>
);
}
enhanceGetInputProps를 사용해 폼이 아직 초기화되지 않았으면 모든 입력에 disabled prop을 추가하는 예시:
import { NumberInput, TextInput, Button } from '@mantine/core';
import { useForm } from '@mantine/form';
interface FormValues {
name: string;
age: number | string;
}
function Demo() {
const form = useForm({
mode: 'uncontrolled',
initialValues: { name: '', age: '' },
enhanceGetInputProps: (payload) => {
if (!payload.form.initialized) {
return { disabled: true };
}
return {};
},
});
return (
<>
<TextInput {...form.getInputProps('name')} label="Your name" />
<NumberInput {...form.getInputProps('age')} label="Age" />
<Button onClick={() => form.initialize({ name: 'John', age: 20 })} mt="md">
Initialize form
</Button>
</>
);
}
폼 초기화 (Initialize form)
호출되면 form.initialize 핸들러가 initialValues와 values를 같은 값으로 설정하고 폼을 초기화된 것으로 표시해요. 이 함수는 한 번만 사용할 수 있어요. 이후의 form.initialize 호출은 무시돼요.
form.initialize는 폼 값을 백엔드 API 응답과 동기화하고 싶을 때 유용해요.
import { Button, NumberInput, TextInput } from '@mantine/core';
import { isInRange, isNotEmpty, useForm } from '@mantine/form';
interface FormValues {
name: string;
age: number | string;
}
function apiRequest(): Promise<{ name: string; age: number }> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'John Doe', age: 25 });
}, 1000);
});
}
function Demo() {
const form = useForm({
mode: 'uncontrolled',
initialValues: { name: '', age: 0 },
validate: {
name: isNotEmpty('Name is required'),
age: isInRange({ min: 18 }, 'You must be at least 18 to register'),
},
});
return (
<>
<TextInput {...form.getInputProps('name')} label="Name" />
<NumberInput {...form.getInputProps('age')} label="Age" />
<Button onClick={() => apiRequest().then((values) => form.initialize(values))} mt="md">
Initialize form
</Button>
</>
);
}
TanStack Query(react-query)와 함께 사용하는 예시:
import { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useForm } from '@mantine/form';
function Demo() {
const query = useQuery({
queryKey: ['current-user'],
queryFn: () => fetch('/api/users/me').then((res) => res.json()),
});
const form = useForm({
mode: 'uncontrolled',
initialValues: {
name: '',
email: '',
},
});
useEffect(() => {
if (query.data) {
// query.data가 바뀌어도 폼은 한 번만 초기화돼요
form.initialize(query.data);
}
}, [query.data]);
}
커스텀 입력과 getInputProps 통합 (Integrate getInputProps with custom inputs)
form.getInputProps는 다음 속성을 가진 객체를 반환해요.
valuedefaultValueonChangeonFocusonBlurerror
form.getInputProps와 동작하는 커스텀 입력을 만들려면 컴포넌트가 이 props를 받아 입력 컴포넌트에 전달하거나 다른 방식으로 사용하는지 확인해요.
커스텀 입력 컴포넌트를 만드는 예시:
interface CustomInputProps {
value?: string;
defaultValue?: string;
onChange?: (event: React.ChangeEvent) => void;
onFocus?: (event: React.FocusEvent) => void;
onBlur?: (event: React.FocusEvent) => void;
error?: string;
}
export function CustomInput({
value,
defaultValue,
onChange,
onFocus,
onBlur,
error,
}: CustomInputProps) {
return (
<div>
<input value={value} defaultValue={defaultValue} onChange={onChange} onFocus={onFocus} onBlur={onBlur} />
{error && <span>{error}</span>}
</div>
);
}
그런 다음 form.getInputProps와 함께 사용해요.
import { useForm } from '@mantine/form';
import { CustomInput } from './CustomInput';
function Demo() {
const form = useForm({
mode: 'uncontrolled',
initialValues: { name: '' },
});
return (
<CustomInput {...form.getInputProps('name')} />
);
}