30K Views
March 24, 23
スライド概要
Webフロントエンドエンジニア
React Hook Form 2023 3 24 ( ) x Zod
React Hook Form ?
React Hook Form React
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),
});
React Hook Form API PR Discussion Close
register? Controller? API …?! …?! …?! …?!
React Hook Form
React Hook Form HTML React Hook Form ( TypeScript )
React Hook Form `UseFormReturn` `zod` `defaultValues` `zod` `FieldValues` Zod
`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
UseFormReturn `useForm< >()`
`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: "",
}, //
});
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
(
`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>;
(
)
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`)} >}
</>
);
};
const profiles = watch("profiles");
useEffect(() => {
trigger("profiles");
}, [trigger, profiles]);
`profiles.[i].isSelected`
`zodResolver` `async` `defaultValue` `reset()` `setValue()` `register()`(uncontrolled component) `trigger()` `<Controller />` (controlled form)
React Hook Form Zod