formularity
Version:
The last React form library you will ever need!
80 lines (79 loc) • 2.9 kB
TypeScript
import { ReactNode } from 'react';
import { DeepKeys, DeepValue, CheckArray } from './utilityTypes';
import { FormValues } from './types';
type FieldListHelpers<TListData extends unknown[]> = {
/**
* Adds a new field to the end of the list
*/
addField: (fieldData: TListData[number]) => void;
/**
* Removes the field at the specified index
*/
removeField: (fieldIndex: number) => void;
/**
* Moves the contents of one field in the list to another index
*/
moveField: (currentFieldIndex: number, newFieldIndex: number) => void;
/**
* Replace the value of a field at the specified index with a new value
*/
replaceField: (fieldIndexToReplace: number, fieldData: TListData[number]) => void;
/**
* Inserts a new field at the specified index
*/
insertField: (fieldIndexToInsert: number, fieldData: TListData[number]) => void;
/**
* Swaps the values of two fields in the list
*/
swapFields: (fieldIndexA: number, fieldIndexB: number) => void;
/**
* Removes the last field in the list
*/
removeLastField: () => void;
/**
* Adds a new field to the beginning of the list
*/
addFieldToBeginning: (fieldData: TListData[number]) => void;
};
export type FieldListProps<TFormValues extends FormValues = FormValues, TFieldName extends DeepKeys<TFormValues> = DeepKeys<TFormValues>, TListData = CheckArray<DeepValue<TFormValues, TFieldName>>> = {
name: TFieldName;
render: (listValue: TListData, fieldListHelpers: CheckArray<TListData, FieldListHelpers<CheckArray<TListData>>>) => ReactNode;
};
/**
* `<FieldList />` is a component that helps you
* render out multiple fields in an array-like (list) fashion
* to help manage values in the form that are grouped together.
* @example
*
* ```jsx
* <FieldList
name='hobbies'
render={ ( hobbies, {
addField
} ) => {
return (
<>
<label>Hobbies</label>
{
hobbies.map( ( _, idx ) => (
<Field
key={ idx }
name={ `hobbies[${ idx }]` }
showErrors
/>
) )
}
<button
onClick={ () => addField( '' ) }
type='button'
>
Add Hobby
</button>
</>
);
} }
/>
* ```
*/
export declare const FieldList: <TFormValues extends FormValues = FormValues, TFieldName extends DeepKeys<TFormValues> = DeepKeys<TFormValues>, TListData = CheckArray<DeepValue<TFormValues, TFieldName>>>({ name, render }: FieldListProps) => ReactNode;
export {};