vamo
vamo
TTCTheo's Typesafe Cult
Created by vamo on 11/29/2023 in #questions
React hook form with zod submit error:
Im trying to implement custom components with react hook form with zod for validation For Input Select RadioButton etc. For now I implemented it for Form Wrapper aswell as Input component but for some reason when I submit I get following errors: email: {message: 'Required', type: 'invalid_type', ref: undefined} name: {message: 'Required', type: 'invalid_type', ref: undefined} Any Ideas why that may be? Here is my implementation, Form wrapper:
import React, { ReactNode } from 'react'
import { FieldValues, SubmitErrorHandler, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ZodType } from 'zod'

interface HookForm {
children: ReactNode
onSubmit: (data: FieldValues) => void
onError: SubmitErrorHandler<FieldValues>
schema: ZodType<any, any, any>
}

export default function HookFormComponent<T extends FieldValues>({
children,
onSubmit,
onError,
schema,
}: HookForm) {
const { handleSubmit } = useForm<T>({
resolver: zodResolver(schema),
})

return <form onSubmit={handleSubmit(onSubmit, onError)}>{children}</form>
}


Input:
import { useForm } from 'react-hook-form'

interface Inputs extends Record<string, unknown> {
name: string
type?: string
placeholder?: string
className?: string
}

export default function HookFormInput(props: Inputs) {
const {
register,
formState: { errors },
} = useForm<Inputs>()

return (
<div>
<input
{...register(props.name)}
id={props.name}
type={props.type}
placeholder={props.placeholder}
className={props.className}
/>
{errors[props.name] && <span>{errors[props.name]?.message}</span>}
</div>
)
}
import React, { ReactNode } from 'react'
import { FieldValues, SubmitErrorHandler, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ZodType } from 'zod'

interface HookForm {
children: ReactNode
onSubmit: (data: FieldValues) => void
onError: SubmitErrorHandler<FieldValues>
schema: ZodType<any, any, any>
}

export default function HookFormComponent<T extends FieldValues>({
children,
onSubmit,
onError,
schema,
}: HookForm) {
const { handleSubmit } = useForm<T>({
resolver: zodResolver(schema),
})

return <form onSubmit={handleSubmit(onSubmit, onError)}>{children}</form>
}


Input:
import { useForm } from 'react-hook-form'

interface Inputs extends Record<string, unknown> {
name: string
type?: string
placeholder?: string
className?: string
}

export default function HookFormInput(props: Inputs) {
const {
register,
formState: { errors },
} = useForm<Inputs>()

return (
<div>
<input
{...register(props.name)}
id={props.name}
type={props.type}
placeholder={props.placeholder}
className={props.className}
/>
{errors[props.name] && <span>{errors[props.name]?.message}</span>}
</div>
)
}
3 replies