Skip to content

Rayologist/rhf-zod-mantine-typescript-template

Repository files navigation

Mantine-styled RHF (React Hook Form) Controlled Components in Typescript and NextJS

This mantine-next-template integrates React Hook Form as a means of form contol and Zod as form validation. Input components developed by Mantine can be easily controlled through <FormController /> as in here.

Sample Form

The useForm Hook

A custom hook useForm is implemented as a wrapper of RHF to solve the problem of boilerplate codes as shown in src/containers/Form.tsx when developers are constructing forms. The sample form is adapted from Mantine UI, and can be found in src/pages/simple-form.tsx.

Usage

Please refer directly to the codes here.

The props are almost the same as useForm in React Hook Form. However, there are three fields required:

  1. defaultvalues: Same as RHF but required
  2. onSubmit: Similar to RHF SubmitHandler in handleSubmit, but comes with an additional context parameter, which is of type UseFormReturn.
  3. controllers: Objects of field props. Required props: control (controlled components), label (Field label), name (HTML input name)

And two optional fields:

  1. schema: Zod schema.
  2. onSubmitError: Similar to RHF SubmitErrorHandler in handleSubmit, but comes with an additional context parameter, which is of type UseFormReturn.

In addition, there are two ways to access RHF useForm returned methods:

  1. Using array destructured value, as exemplified here.
  2. Using render props as shown in here.

Moreover, submit button for the form can be accessed using dot notation [example]. The only difference between this one and that of mantine is that id and loaderProps are already passed to the button props, as shown in here, so that the button does not have to live inside html form tag, such as this one.

Current List of Controlled Components from Mantine

Getting Started

First, run the development server:

pnpm dev
# or
npm run dev
# or
yarn dev

Open http://localhost:3000 with your browser to see the result.

Contact

If you have any questions, please feel free to file issues or contact me at rayologist1002@gmail.com

About

NextJS template: Typescript, Mantine, React Hook Form, and Zod.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages