Skip to main content

useInput

useInput is used to declare a local field.

Parameters

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

PropertyTypeDefaultDescription
defaultValueunknownDefault value for the associated field (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)
onBlurOptOutbooleanOpt-out for native onBlur event for this field
onChangeOptOutbooleanOpt-out for native onChange event for this field (see controlled components guide for more information)
transformer(value: unknown) => unknownTransformer for type casting (see local fields guide for more information)
validatorIValidator | 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:

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, 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>
);
}