useInputState
A custom hook for managing the state of an input field.
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 | Initial input value |
options | UseInputStateOptions | Options object |
Options
| Name | Type | Default | Description |
|---|---|---|---|
validate | (value: string) => string | null | undefined | - | Validation function; returns an error message string if invalid, or null/undefined if valid |
Returns
| Name | Type | Description |
|---|---|---|
value | string | Current input value |
error | string | null | Validation error message, or null if there is no error |
onChange | (e: ChangeEvent<HTMLInputElement>) => void | Change event handler for the input |
resetError | () => void | Resets only the error state |
resetValue | () => void | Resets only the value state |
reset | () => void | Resets 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: