@xtreamsrl/react-forms
v0.2.0
Published
This package exposes a FormProvider and the following hooks: useForm, useFormContext, useController. It is useful to ease form management.
Downloads
505
Readme
@xtreamsrl/react-forms
This package exposes a FormProvider and the following hooks: useForm, useFormContext, useController. It is useful to ease form management.
Installation
npm install @xtreamsrl/react-forms
Usage
In order to use this library properly it is advantageous to follow the description of the single hooks. They are listed in an order that allows to add each required piece step by step.
useForm
First thing first, it is necessary to rely on the useForm
hook to have access to methods and properties to manage and control forms.
This hook is used to encapsulate the logic and state related to form management.
The useForm hook accepts an object containing two fields:
initialValues
to populate the entire form with default values.validationSchema
to integrate yup inputs' validation.
! Caution: At the moment only
yup
is accepted as validator, despite react-hook-form supports Yup, Zod, Joi, Vest, Ajv and many others.
import {useForm} from "@xtreamsrl/react-forms"
import * as yup from "yup"
const validationSchema = yup.object().shape({
email: yup.string().email().required("Required"),
password: yup.string().min(5, "Password is too short").required("Required"),
});
See yup on GitHub to know more about validation.
const form = useForm<LoginData>({initialValues: {email: "", password: ""}, validationSchema});
The useForm
return value has three fields:
formProps
contains methods to handle the form. The following two fields are subfields of this object.formState
is an object that contains information about the entire form state. It helps to keep on track with the user's interaction with the form application.reset
allows to reset the entire form state, fields reference, and subscriptions. It also allows partial reset through optional parameters.
FormProvider
Once form management methods are available, it is possible to define a form that will be wrapped using a provider.
When wrapping the form, it can be helpful to specify the object type to be handled.
In other terms, it can be specified the TypeScript type of the fields that make up the entire form.
For example, LoginData has been defined from the validation schema: type LoginData = yup.InferType<typeof validationSchema>
and specified to the Provider.
Then, it requires formProps
, containing all the methods returned by the useForm
hook.
import {FormProvider} from "@xtreamsrl/react-forms"
<FormProvider<LoginData> {...form.formProps}>
<form onSubmit={form.formProps.handleSubmit((values, event) => {
event?.preventDefault();
login(values.email, values.password)
})}>
<Input name="email" type="email" placeholder="email"/>
<Input name="password" type="password" placeholder="password"/>
<Button type="submit">Login</Button>
</form>
</FormProvider>
See the useController blow to see an example of how to define the Input component visible in this snippet.
useController
This hook is used to bind a single input field to the form, it powers the Controller
. It provides a way to manually control an input field while still integrating with the overall form state.
The Controller
component is a wrapper around the input component that works with the useController
hook.
The hook accepts an object containing:
- name: unique name of the input, it is the only required field.
- control: control object provided by invoking useForm. Optional when using FormProvider.
- rules.
- shouldUnregister: value that indicate that the Input will be unregistered after unmount and defaultValues will be removed as well.
- defaultValue: it cannot be
undefined
.
import {useController} from "@xtreamsrl/react-forms"
export function Input({name, type, placeholder}: {
name: string, type: string, placeholder: string
}) {
const {
field: {
ref,
value,
...inputProps
},
fieldState: {
error,
invalid
}
} = useController({name});
return
<div>
<input placeholder={placeholder} type={type} {...inputProps}/>
<span> {error?.message?.toString()} </span>
</div>
}
The useController
return values (field, fieldState and formState) can be explored in the dedicated page of the react-hook-form documentation, given that this hook return values have not been manipulated before being returned.
useFormContext
This custom hook allows to access the form context. useFormContext
is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop.
It returns setError
, watch
, formState
.
Remember that it is necessary to wrap the form with the FormProvider component for useFormContext
to work properly.
import { useForm, FormProvider, useFormContext } from "@xtreamsrl/react-forms"
export default function App() {
const {formProps: methods} = useForm()
const onSubmit = (data) => console.log(data)
return (
<FormProvider {...methods}>
// pass all methods into the context
<form onSubmit={methods.handleSubmit(onSubmit)}>
{/*...*/}
<NestedInput />
<input type="submit" />
</form>
</FormProvider>
)
}
function NestedInput({name: string}) {
const {setError, watch, formState} = useFormContext()
const value = watch(name);
const companyName = watch('companyName');
const companyAddress = watch('companyAddress');
const invalid = name in formState.errors;
// ...
}
The watch
method watches specified inputs and return their values.
It is useful to render input value and for determining what to render by condition. See more on the documentation page.
The setError
function allows you to manually set one or more errors. See more about setError.