use-validated-state
use-validated-state
값과 검증(validation) 상태를 함께 관리하는 훅이에요. 현재 값, 마지막 유효 값, 유효 여부를 반환해요.
출처: 문서
본문
사용법 (Usage)
useValidatedState 훅에 초기 값과 검증 함수를 넘겨주면, 현재 값(value), 마지막 유효 값(lastValidValue), 유효 여부(valid)를 얻을 수 있어요:
import { TextInput, Text, Box } from '@mantine/core';
import { useValidatedState } from '@mantine/hooks';
function Demo() {
const [{ value, lastValidValue, valid }, setEmail] = useValidatedState(
'',
(val) => /^\S+@\S+$/.test(val),
true
);
return (
setEmail(event.currentTarget.value)}
withAsterisk
error={!valid}
placeholder="[email protected]"
label="Your email"
/>
Current value:
{' '}
{value || '[empty string]'}
Last valid value:
{' '}
{lastValidValue || '[empty string]'}
);
}
정의 (Definition)
interface UseValidatedStateValue<T> {
/** Current value */
value: T;
/** Last valid value */
lastValidValue: T | undefined;
/** True if the current value is valid; false otherwise */
valid: boolean;
}
type UseValidatedStateReturnValue<T> = [
/** Current value */
UseValidatedStateValue<T>,
/** Handler to update the state, passes `value` and `payload` to `onChange` */
(value: T) => void,
];
function useValidatedState<T>(
initialValue: T,
validate: (value: T) => boolean,
initialValidationState?: boolean,
): UseValidatedStateReturnValue<T>
내보내는 타입 (Exported types)
UseValidatedStateValue와 UseValidatedStateReturnValue 타입은 @mantine/hooks에서 내보내져요:
import type { UseValidatedStateValue, UseValidatedStateReturnValue } from '@mantine/hooks';