React Hook Form と Zod を使うときの注意点

29.8K Views

March 24, 23

スライド概要

profile-image

Webフロントエンドエンジニア

シェア

またはPlayer版

埋め込む »CMSなどでJSが使えない場合

関連スライド

各ページのテキスト
1.

React Hook Form 2023 3 24 ( ) x Zod

3.

React Hook Form ?

4.

React Hook Form React

5.
[beta]
Zod
JS
React Hook Form
=>
import { z } from "zod";
const schema = z.object({
name: z.string(),
email: z.string().email(),
});
type SchemaType = z.infer<typeof schema>;
const methods = useForm<SchemaType>({
resolver: zodResolver(schema),
});

6.

React Hook Form API PR Discussion Close

7.

register? Controller? API …?! …?! …?! …?!

8.

React Hook Form

9.

React Hook Form HTML React Hook Form ( TypeScript )

10.

React Hook Form `UseFormReturn` `zod` `defaultValues` `zod` `FieldValues` Zod

11.
[beta]
`UseFormReturn`
`FieldValues`
FieldValues

RHF

`register('name')`

key
`'name'`

`FieldValues`

type Props<T extends FieldValues> = {
name: FieldValue<T>;
};
export const CheckBox = <T extends FieldValues>({ name }: Props<T>) => {
const { register } = useFormContext<T>();
return <input type="checkbox" {...register(name)} />;
};

RFH

13.
[beta]
`zod`

`defaultValues`

const profileSchema = z.object({
name: z.string(),
email: z.string().email(),
});
type SchemaType = z.infer<typeof profileSchema>;
const methods = useForm<SchemaType>({
resolver: zodResolver(schema),
defaultValues: {
name: "",
email: "",
}, //
});

14.
[beta]
defaultValue
…
unde ned
…?
useForm

React Hook Form

https://zenn.dev/kazu013/articles/ad2e81e1c12dcd
OK
const methods = useForm<
UseFormProps<SchemaType> & { defaultValues: SchemaType }
>({
resolver: zodResolver(RequestSchema),
defaultValues: {
name: "",
email: "",
},
});

defaultValues

15.
[beta]
(

`zod`

)

const schema = z.object({
profiles: z
.array(
z.object({
name: z.string({ message: "
" }),
isSelected: z.boolean(),
})
)
.refine(
(array) =>
Array.isArray(array) && array.some(({ isSelected }) => isSelected),
{
message: "1
",
}
),
});
type SchemaType = z.infer<typeof schema>;

16.
[beta]
(

)
const Component = () => {
const { register } = useForm<SchemaType>({
resolver: zodResolver(schema),
defaultValues: {
name: '',
email: ''
},
});
return (
<>
{items.map(item,i) => <input key={item.name} type="checkbox" {...register(`profiles.[i].isSelected`)} >}
</>
);
};

17.
[beta]
const profiles = watch("profiles");
useEffect(() => {
trigger("profiles");
}, [trigger, profiles]);

`profiles.[i].isSelected`

18.

`zodResolver` `async` `defaultValue` `reset()` `setValue()` `register()`(uncontrolled component) `trigger()` `<Controller />` (controlled form)

19.

React Hook Form Zod