Skip to content

Advanced

Build complex and accessible forms

Accessibility (A11y)

React Hook Form has support for native form validation, which lets you validate inputs with your own rules. Since most of us have to build forms with custom designs and layouts, it is our responsibility to make sure those are accessible (A11y).

The following code example works as intended for validation; however, it can be improved for accessibility.

The following code example is an improved version by leveraging ARIA.

After this improvement, the screen reader will say: “Name, edit, invalid entry, This is required.”


Wizard Form / Funnel

It's pretty common to collect user information through different pages and sections. We recommend using a state management library to store user input through different pages or sections. In this example, we are going to use little state machine as our state management library (you can replace it with redux if you are more familiar with it).

Step 1: Set up your routes and store.

Step 2: Create your pages, collect and submit the data to the store and push to the next form/page.

Step 3: Make your final submission with all the data in the store or display the resulting data.

Following the above pattern, you should be able to build a wizard form/funnel to collect user input data from multiple pages.


Smart Form Component

This idea here is that you can easily compose your form with inputs. We are going to create a Form component to automatically collect form data.

Let's have a look what's in each of those components.

Form

The Form component's responsibility is to inject all react-hook-form methods into the child component.

Input / Select

Those input components' responsibility is to registering them into react-hook-form.

With the Form component injecting react-hook-form's props into the child component, you can easily create and compose complex forms in your app.


Error Messages

Error messages are visual feedback to our users when there are issues with their inputs. React Hook Form provides an errors object to let you retrieve errors easily. There are several different ways to improve error presentation on the screen.

  • Register

    You can simply pass the error message to register, via the message attribute of the validation rule object, like this:

    <input {...register('test', { maxLength: { value: 2, message: "error message" } })} />

  • Optional Chaining

    The ?. optional chaining operator permits reading the errors object without worrying about causing another error due to null or undefined.

    errors?.firstName?.message

  • Lodash get

    If your project is using lodash, then you can leverage the lodash get function. Eg:

    get(errors, 'firstName.message')


Connect Form

When we are building forms, there are times when our input lives inside of deeply nested component trees, and that's when FormContext comes in handy. However, we can further improve the Developer Experience by creating a ConnectForm component and leveraging React's renderProps. The benefit is you can connect your input with React Hook Form much easier.


FormProvider Performance

React Hook Form's FormProvider is built upon React's Context API. It solves the problem where data is passed through the component tree without having to pass props down manually at every level. This also causes the component tree to trigger a re-render when React Hook Form triggers a state update, but we can still optimise our App if required via the example below.

Note: Using React Hook Form's Devtools alongside FormProvider can cause performance issues in some situations. Before diving deep in performance optimizations, consider this bottleneck first.


Controlled mixed with Uncontrolled Components

React Hook Form embraces uncontrolled components and is also compatible with controlled components. Most UI libraries are built to support only controlled components, such as Material-UI and Antd. Besides, with React Hook Form the re-rendering of controlled component is also optimized. Here is an example that combines them both with validation.


Custom Hook with Resolver

You can build a custom hook as a resolver. A custom hook can easily integrate with yup/Joi/Superstruct as a validation method, and to be used inside validation resolver.

  • Define a memoized validation schema (or define it outside your component if you don't have any dependencies)

  • Use the custom hook, by passing the validation schema

  • Pass the validation resolver to the useForm hook


Working with virtualized lists

Imagine a scenario where you have a table of data. This table might contain hundreds or thousands of rows, and each row will have inputs. A common practice is to only render the items that are in the viewport, however this will cause issues as the items are removed from the DOM when they are out of view, and re-added. This will cause items to reset to their default values when they re-enter the viewport.

An example is shown below using react-window.


Testing Form

Testing is very important because it prevents your code from having bugs or mistakes, and guarantees code safety when refactoring the codebase.

We recommend using testing-library, because it is simple and tests are more focused on user behavior.

Step 1: Set up your testing environment.

Please install @testing-library/jest-dom with the latest version of jest, because react-hook-form uses MutationObserver to detect inputs, and to get unmounted from the DOM.

Note: If you are using React Native, you don't need to install @testing-library/jest-dom.

Create setup.js to import @testing-library/jest-dom.

Note: If you are using React Native, you need to create setup.js, define window object, and include the following lines in the setup file:

Finally, you have to update setup.js in jest.config.js to include the file.

Step 2: Create login form.

We have set the role attribute accordingly. These attributes are helpful for when you write tests, and they improve accessibility. For more information, you can refer to the testing-library documentation.

Step 3: Write tests.

The following criteria are what we try to cover with the tests:

  • Test submission failure.

    We are using waitFor and find* methods to detect submission feedback, because the handleSubmit method is executed asynchronously.

  • Test validation associated with each inputs.

    We are using the *ByRole method when querying different elements because that's how users recognize your UI component.

  • Test successful submission.

Resolving act warning during test

If you test a component that uses react-hook-form, you might run into a warning like this, even if you didn't write any asynchronous code for that component:

Warning: An update to MyComponent inside a test was not wrapped in act(...)

In this example, there is a simple form without any apparent async code, and the test merely renders the component and tests for the presence of a button. However, it still logs the warning about updates not being wrapped in act().

This is because react-hook-form internally uses asynchronous validation handlers. In order to compute the formState, it has to initially validate the form, which is done asynchronously, resulting in another render. That update happens after the test function returns, which triggers the warning.

To solve this, wrap your render() calls in await act(async () => {}):


Transform and Parse

The native input returns the value in string format unless invoked with valueAsNumber or valueAsDate, you can read more under this section. However, it's not perfect, we still have to deal with isNaN or null values. So it's better to leave the transform at the custom hook level. In the following example, we are using the Controller to include the functionality of the transform value's input and output. You can also achieve a similar result with a custom register.

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit