Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/konradmi/zod-hook-form

react-hook-form + zod wrapper
https://github.com/konradmi/zod-hook-form

forms react-hook-form typescript validation zod

Last synced: 14 days ago
JSON representation

react-hook-form + zod wrapper

Awesome Lists containing this project

README

        

## zod-hook-form

Thin wrapper over react-hook-form and zod. Types are infered based on the provided zod schema. It also provides helpers for dealing with:
- form inputs
- form arrays
- custom form components

### Examples

- A login form:

```
import * as z from 'zod'

import { ZodForm, ZodFormInput, ZodFormSubmitButton, ZodFormCancelButton, ZodFormSubmitError } from 'zod-hook-form'

import './LoginForm.css'

const schema = z.object({
username: z.string().min(3, { message: 'Too short'}).max(20, { message: 'Too long'}),
password: z.string().min(3, { message: 'Too short'}).max(20, { message: 'Too long'}),
})

const initialValues = {
username: '',
password: '',
}

const LoginForm = () => {
const handleSubmit = async (values: z.infer) => {
console.log('values', values)
}

return (


Username



Password





)
}
```

- A custom form input:

```
import { ZodFormElement } from 'zod-hook-form'
import type { ComponentProps, ZodFormElementProps } from 'zod-hook-form'

const Input = ({ value, onChange, onBlur, error, ...rest }: ComponentProps) => {
return (
onChange(e.target.value)}
onBlur={onBlur}
{...rest}
/>
)
}

```

Somewhere in the form:

```
...

...

```

- Integration with 3rd party libraries:

```
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

import { ZodFormElement, ZodForm, ZodFormInput, ZodFormSubmitButton, ZodFormCancelButton } from 'zod-hook-form'
import type { ComponentProps } from 'zod-hook-form'

const MUISelect = ({ value, onChange, onBlur, error, ...rest }: ComponentProps) => {
return (

Age
onChange(+e.target.value)}
{...rest}
>
Ten
Eighteen
Twenty
Thirty


)
}
```
Somewhere in the form:

```
...

...

```

To run the examples:

```
cd examples
yarn
yarn run dev
```