Skip to content

useField ​

Hook to manage a form field

utilities
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { useField } from '@siberiacancode/reactuse';

Usage ​

typescript
const { register, getValue, setValue, reset, dirty, error, setError, clearError, touched, focus, watch } = useField();

Demo ​

Api ​

Parameters

NameTypeDefaultNote
params.initialValue?Value-Initial value
params.initialTouched?booleanfalseInitial touched state
params.autoFocus?booleanfalseAuto focus
params.validateOnChange?booleanfalseValidate on change
params.validateOnBlur?booleanfalseValidate on blur
params.validateOnMount?booleanfalseValidate on mount

Returns

UseFieldReturn<Value>

Type declaration ​

typescript
export interface UseFieldParams<Value> {
  /** The auto focus */
  autoFocus?: boolean;
  /** The initial touched */
  initialTouched?: boolean;
  /** The initial value */
  initialValue?: Value;
  /** The validate on blur */
  validateOnBlur?: boolean;
  /** The validate on mount */
  validateOnChange?: boolean;
  /** The validate on mount */
  validateOnMount?: boolean;
}

export interface UseFieldRegisterParams {
  /** The required validation */
  required?: string;
  /** The custom validation */
  validate?: (value: string) => Promise<string | true>;
  /** The min value validation */
  max?: {
    value: number;
    message: string;
  };
  /** The max length validation */
  maxLength?: {
    value: number;
    message: string;
  };
  /** The max value validation */
  min?: {
    value: number;
    message: string;
  };
  /** The min length validation */
  minLength?: {
    value: number;
    message: string;
  };
  /** The pattern validation */
  pattern?: {
    value: RegExp;
    message: string;
  };
}

export interface UseFieldReturn<Value> {
  /** The dirty state */
  dirty: boolean;
  /** The error state */
  error?: string;
  /** The set error function */
  touched: boolean;
  /** The set error function */
  clearError: () => void;
  /** The focus function */
  focus: () => void;
  /** The get value function */
  getValue: () => Value;
  /** The register function */
  register: (params?: UseFieldRegisterParams) => {
    onBlur: () => void;
    onChange: () => void;
    ref: (
      node: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null | undefined
    ) => void;
  };
  /** The reset function */
  reset: () => void;
  /** The set error function */
  setError: (error: string) => void;
  /** The  set value function */
  setValue: (value: Value) => void;
  /** The watch function */
  watch: () => Value;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
H
hywax
hywax

Released under the MIT License.