useInput
useInput
is used to declare a local field.
Parameters
useInput
takes only one parameter that is an object with the following shape:
Property | Type | Default | Description |
---|---|---|---|
defaultValue | unknown | Default value for the associated field (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 | boolean | Opt-out for native onBlur event for this field | |
onChangeOptOut | boolean | Opt-out for native onChange event for this field (see controlled components guide for more information) | |
transformer | (value: unknown) => unknown | Transformer for type casting (see local fields guide for more information) | |
validator | IValidator | IValidatorObject | Record<string, IValidator | IValidatorObject> | Local validators (see validation guide for more information) |
See here for the types.
Returns
useInput
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, useInput } from '@per-form/react';
const validator = (values: IFormValues) =>
String(values.text).includes('foo') ? '' : 'Value does not include "foo"';
function Input() {
const { errors } = useInput({ id: 'toto', name: 'text', validator });
return (
<>
<input name="text" required />
{errors.all.text && <div className="error">{errors.all.text}</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}>
<Input />
<button type="submit">Submit</button>
</form>
</FormProvider>
);
}