본문으로 건너뛰기

useInputState

input 필드의 상태를 관리하는 커스텀 훅 입니다.


Code

🔗 실제 구현 코드 확인


Interface

typescript
interface UseInputStateOptions {
validate?: (value: string) => string | null | undefined;
}

interface UseInputStateReturn {
value: string;
error: string | null;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
resetError: () => void;
resetValue: () => void;
reset: () => void;
}
typescript
function useInputState(
initialValue?: string,
options?: UseInputStateOptions
): UseInputStateReturn;

Parameters

NameTypeDescription
initialValuestring초기 입력 값
optionsUseInputStateOptions옵션 객체

Options

NameTypeDefaultDescription
validate(value: string) => string | null | undefined-유효성 검사 함수. 유효하지 않으면 에러 메시지 문자열을 반환하고, 유효하면 null 또는 undefined를 반환합니다

Returns

NameTypeDescription
valuestring현재 입력 값
errorstring | null유효성 검사 에러 메시지, 에러가 없으면 null
onChange(e: ChangeEvent<HTMLInputElement>) => voidinput의 change 이벤트 핸들러
resetError() => void에러 상태만 초기화하는 함수
resetValue() => void값 상태만 초기화하는 함수
reset() => void값과 에러 상태를 모두 초기화하는 함수

Usage

typescript
import { useInputState } from '@modern-kit/react';

const Example = () => {
const { value, error, onChange, reset } = useInputState('', {
validate: (value) => value.length > 10 ? 'value는 10자 이상이면 안됩니다.' : undefined
});

return (
<>
<h1>{value}</h1>
<p>{error}</p>
<input type="text" name="test" onChange={onChange} value={value} />
<button onClick={reset}>reset</button>
</>
);
};

Example

test:

error: