useInputs
useInputs
is used to declare local fields.
Parameters
useInputs
takes only one parameter that is an object with the following shape:
Property | Type | Default | Description |
---|---|---|---|
defaultValues | Record<string, unknown> | Default values for local fields (see local fields guide for more information) | |
id | string | Id associated to the validator (if there is only one validator) | |
messages | Record<string, string> | Custom messages (see messages guide for more information) | |
name * | string | Name of the local field (also used as id if id is not provided) | |
onBlurOptOut | string[] | string | Opt-out for native onBlur event | |
onChangeOptOut | string[] | string | Opt-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) | |
validators | IValidator | 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:
Property | Type | Description |
---|---|---|
error | IMainError | The main error associated with the field |
errors | IError | Field errors (see errors guide for more information) |
onChange | IOnChangeHandler | Change handler (see type casting guide and controlled components guide for more information) |
onError | IOnErrorHandler | Manual error handler (see controlled components guide for more information) |
onReset | IOnResetHandler | Reset handler (see reset guide for more information) |
onSubmit | IOnSubmitHandler | Submit handler (see submit guide for more information) |
watch | IWatch | Manual 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>
);
}