CodexBloom - Programming Q&A Platform

React Hook Form with TypeScript: Submit not triggering for nested fields

πŸ‘€ Views: 31 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
react typescript react-hook-form

I'm migrating some code and I'm having trouble with I'm implementing a form using React Hook Form (v7) with TypeScript, but I'm running into an issue where the submit handler is not triggering for nested fields inside an object... My form has a structure like this: ```typescript interface FormData { user: { name: string; email: string; }; preferences: { newsletter: boolean; notifications: boolean; }; } ``` I'm using `register` to bind the inputs but when I try to submit the form, the `onSubmit` function does not get called. Here’s the relevant portion of my form code: ```typescript const { register, handleSubmit } = useForm<FormData>(); const onSubmit = (data: FormData) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('user.name')} placeholder="Name" /> <input {...register('user.email')} placeholder="Email" /> <label> <input type="checkbox" {...register('preferences.newsletter')} /> Subscribe to newsletter </label> <label> <input type="checkbox" {...register('preferences.notifications')} /> Enable notifications </label> <button type="submit">Submit</button> </form> ); ``` I have verified that React Hook Form is correctly set up and I can log the `data` object when calling `onSubmit`. However, the handler does not seem to fire if I leave any of the nested fields empty. Instead, I get a console warning that says "Expected a function for `onSubmit`, but got undefined." I've tried different ways to register the nested fields, including using dot notation as shown, and also tried destructuring the `register` function. I also checked that I have the latest version of React Hook Form (7.39.0). Any insights on how to ensure the submit handler gets triggered regardless of the nested field values would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Is there a simpler solution I'm overlooking? This is part of a larger service I'm building. Thanks, I really appreciate it!