Skip to main content

useInputState

A custom hook for managing the state of an input field.


Code

🔗 View source 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
initialValuestringInitial input value
optionsUseInputStateOptionsOptions object

Options

NameTypeDefaultDescription
validate(value: string) => string | null | undefined-Validation function; returns an error message string if invalid, or null/undefined if valid

Returns

NameTypeDescription
valuestringCurrent input value
errorstring | nullValidation error message, or null if there is no error
onChange(e: ChangeEvent<HTMLInputElement>) => voidChange event handler for the input
resetError() => voidResets only the error state
resetValue() => voidResets only the value state
reset() => voidResets both value and error state

Usage

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

const Example = () => {
const { value, error, onChange, reset } = useInputState('', {
validate: (value) => value.length > 10 ? 'Value must not exceed 10 characters.' : undefined
});

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

Example

test: