Skip to main content

useInputs

useInputs is used to declare local fields.

Parameters

useInputs takes only one parameter that is an object with the following shape:

PropertyTypeDefaultDescription
defaultValuesRecord<string, unknown>Default values for local fields (see local fields guide for more information)
idstringId associated to the validator (if there is only one validator)
messagesRecord<string, string>Custom messages (see messages guide for more information)
name *stringName of the local field (also used as id if id is not provided)
onBlurOptOutstring[] | stringOpt-out for native onBlur event
onChangeOptOutstring[] | stringOpt-out for native onChange event (see controlled components guide for more information)
transformers<string, (value: unknown) => unknown>Transformers for type casting (see local fields guide for more information)
validatorsIValidator | IValidatorObject | Record<string, IValidator | IValidatorObject>Local validators (see validation guide for more information)

See here for the types.

Returns

useInputs returns an object with the following shape:

PropertyTypeDescription
errorIMainErrorThe main error associated with the field
errorsIErrorField errors (see errors guide for more information)
onChangeIOnChangeHandlerChange handler (see type casting guide and controlled components guide for more information)
onErrorIOnErrorHandlerManual error handler (see controlled components guide for more information)
onResetIOnResetHandlerReset handler (see reset guide for more information)
onSubmitIOnSubmitHandlerSubmit handler (see submit guide for more information)
watchIWatchManual watch function (see watch guide for more information)

See here for the types.

Usage

0
import type { FormEvent } from 'react';
import type { IFormValues } from '@per-form/react';
import type { IProps } from '../types';
import { FormProvider, useForm, useInputs } from '@per-form/react';

const validator = (values: IFormValues) =>
Number(values.a) + Number(values.b) === 42
? ''
: 'The sum must be equal to 42';
const names = ['a', 'b'];

function Inputs() {
const { errors } = useInputs({ names, validators: validator });
return (
<>
<input name="a" required type="number" />
<input name="b" required type="number" />
{errors.validator['a,b']?.error && (
<div className="error">{errors.validator['a,b'].error}</div>
)}
</>
);
}

export default function Demo(props: IProps) {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}

const { formProps, ...context } = useForm({
...props,
onSubmit: handleSubmit,
});

return (
<FormProvider {...context}>
<form {...formProps}>
<Inputs />
<button type="submit">Submit</button>
</form>
</FormProvider>
);
}