What causes React Hook Form to return undefined upon submission?

I am currently working on a project using TypeScript. In this project, I have a form that should output 4 values after submitting the form. However, only the input field linked to the controller is sending a value, while the others are returning undefined:

{title: undefined, description: undefined, rating: 4, name: undefined} //from my console log

This is how my form interface looks like:

export interface IReviewForm {
    name: string;
    title: string;
    description: string;
    rating: number;
}

Here is my form setup:

const { register, control, handleSubmit } = useForm<IReviewForm>();

const onSubmit = (data: IReviewForm) => {
    console.log(data);
};

return (
    <form onSubmit={handleSubmit(onSubmit)}>
        <div>
            <Input {...register('name')} />
            <Input {...register('title')} />
            <div>
                <Controller
                    control={control}
                    name='rating'
                    render={({ field }) => (
                        <Rating isEditable rating={field.value} setRating={field.onChange} />
                    )}
                />
            </div>
            <Textarea  {...register('description')} />
            <div>
                <Button>Send</Button> <!-- submit button -->
            </div>
        </div>
    </form>
);

This is what my package.json file includes:

"dependencies": {
    "next": "11.0.1",
    "react": "17.0.2",
    "react-hook-form": "^7.3.4",
    ...
},
"devDependencies": {
    "@types/react": "^17.0.3",
    "typescript": "^4.2.3"
    ...
}

P.S. Running `npm i` after deleting `node_modules` and `package-lock` files did not resolve the issue.

EDIT: The form works with normal inputs. Even though my Input tag seems to be a normal input without children:

return (
    <input className={cn(className, styles.input)} {...props} />
);

Answer №1

To create your own custom Input component, you can utilize the React.forwardRef method like so:

const Input = React.forwardRef((props, ref) => <input className={cn(className, styles.input)} {...props} ref={ref}/>)

Keep in mind that this implementation is strictly in JavaScript and does not take type considerations into account as your issue isn't related to types.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

using the ts-migrate-mongoose package for migrating MongoDB

I'm currently working on a NestJS application and using ts-migrate-mongoose for database migration. The issue I'm facing is related to importing a user schema from outside of the migration folder (which is located in the root folder by default). ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

What is the significance of utilizing generic types as values within a generic class?

Why is the compiler giving an error for the following code T' only refers to a type, but is being used as a value here: class Factory<T> { create(TCreator: (new () => T)): T { return new TCreator(); } test(json: string) ...

Having trouble with vscode compiling the typescript file?

Even though I diligently followed the tutorial provided by vscode on compiling typescript code, I encountered a problem. The configurations were set up as per the instructions in the tutorial, but when I tried to run the code without debugging, I received ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Restricting the data type of a parameter in a TypeScript function based on another parameter's value

interface INavigation { children: string[]; initial: string; } function navigation({ children, initial }: INavigation) { return null } I'm currently working on a function similar to the one above. My goal is to find a way to restrict the initi ...

NextJs is leading the way with its fantastic PWA support

Our goal is to create a react web application that can function fully offline. Typically, we utilize NextJS for our projects. We are currently facing an issue where we are unable to precache all routes of the application, even if they do not use server-si ...

Exploring Angular2's DOMContentLoaded Event and Lifecycle Hook

Currently, I am utilizing Angular 2 (TS) and in need of some assistance: constructor(public element:ElementRef){} ngOnInit(){ this.DOMready() } DOMready() { if (this.element) { let testPosition = this.elemen ...

How to extract the complete URL from the API endpoint in nextjs

I'm curious if there is a way to fetch the complete URL of the current request within the API route (pages/api/myapi). The only response I have found that comes close to what I need is the req.headers.referer, but I am uncertain if this value will alw ...

A universal TypeScript type for functions that return other functions, where the ReturnType is based on the returned function's ReturnType

Greetings to all TypeScript-3-Gurus out there! I am in need of assistance in defining a generic type GuruMagic<T> that functions as follows: T represents a function that returns another function, such as this example: fetchUser(id: Id) => (disp ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

Transform Dictionary JSON into Typescript model

How can I convert the provided JSON structure into a TypeScript interface to ensure type safety? { "attributes1": { "myKey1": { "myinnerKey11": { "value": "value 1", "name&q ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

Is middleware sufficient to safeguard both the API route and application?

Hey there, I have a question regarding the effectiveness of middleware in protecting an application. Let's say I have api routes and server actions to interact with my database, but only the /dashboard route makes use of these elements. Should I inclu ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

Struggling to successfully pass a function as an argument to the setTimeout method within an array in node.js using TypeScript

Here is an example that successfully demonstrates a function being called using setTimeout: function displayMessage(msg: string){ console.log(msg); } setTimeout(displayMessage, 1000, ["Hi!"]; After one second, it will print out "Hi!" to the console. ...

The src property is missing from the Next.js image

I encountered the following error: Error: Image is missing src property. I'm unsure of what went wrong as it was working fine with the existing code. The error occurred after I closed VSCode and reopened it shortly afterwards. Here are my code snip ...