UNPKG

react-formal

Version:

Classy HTML form management for React

87 lines (86 loc) 2.54 kB
import { Errors } from './types'; import { FieldMeta, UseFieldMetaOptions } from './useField'; export type FieldArrayMeta = FieldMeta; export interface FieldArrayHelpers<T = any> { /** Add an item to the beginning of the array */ unshift(item: T): void; /** * Add an item to the end of the array * @deprecated use `push` */ add(item: T): void; /** Add an item to the end of the array */ push(item: T): void; /** Insert an item at the provided index */ insert(item: T, index: number): void; /** Move an item to a new index */ move(item: T, toIndex: number): void; /** Remove an item from the list */ remove(item: T): void; /** * update or replace an item with a new one. */ update(item: T, oldItem: T): void; onItemError(name: string, errors: Errors): void; } export type UseFieldArrayOptions = Omit<UseFieldMetaOptions, 'validates'> & { validates?: string | string[] | null; }; /** * Retrieve the values at a given path as well as a set of array helpers * for manipulating list values. * * ```jsx * function ContactList() { * const [values, arrayHelpers, meta] = useFieldArray("contacts") * * return ( * <ul> * {values.map((value, idx) => ( * <li key={value.id}> * <Form.Field name={`contacts[${idx}].name`} /> * * <button onClick={() => arrayHelpers.remove(value)}> * Remove * </button> * </li> * )} * </ul> * ) * } * ``` * * @param name A field path, should point to an array value in the form data */ declare function useFieldArray<T = any>(name: string): [T[], FieldArrayHelpers<T>, FieldMeta]; /** * Retrieve the values at a given path as well as a set of array helpers * for manipulating list values. * * ```jsx * function ContactList() { * const [values, arrayHelpers, meta] = useFieldArray({ * name: 'contacts', * validates: 'otherField' * }) * * return ( * <ul> * {values.map((value, idx) => ( * <li key={value.id}> * <Form.Field name={`contacts[${idx}].name`} /> * * <button onClick={() => arrayHelpers.remove(value)}> * Remove * </button> * </li> * )} * </ul> * ) * } * ``` * * @param name A field path, should point to an array value in the form data */ declare function useFieldArray<T = any>(options: UseFieldArrayOptions): [T[], FieldArrayHelpers<T>, FieldMeta]; export default useFieldArray;