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
| Name | Type | Description |
|---|---|---|
initialValue | string | 초기 입력 값 |
options | UseInputStateOptions | 옵션 객체 |
Options
| Name | Type | Default | Description |
|---|---|---|---|
validate | (value: string) => string | null | undefined | - | 유효성 검사 함수. 유효하지 않으면 에러 메시지 문자열을 반환하고, 유효하면 null 또는 undefined를 반환합니다 |
Returns
| Name | Type | Description |
|---|---|---|
value | string | 현재 입력 값 |
error | string | null | 유효성 검사 에러 메시지, 에러가 없으면 null |
onChange | (e: ChangeEvent<HTMLInputElement>) => void | input의 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: