When using React Hook Form with TypeScript, the error message "Property 'inputRef' does not exist on type DetailedHTMLProps" may arise

This is my custom react-hook controller component written with TypeScript

      <Controller
        control={control}
        name={name}
        defaultValue={defaultValue}
        rules={validate}
        ref={register({
          validate
        })}
        render={props => (
          <input
            name={props.name}
            value={props.value}
            ref={props.ref}
            type={'text'}
            placeholder={label}
            aria-label={label}
            onChange={handleChange}
            data-error={errorText !== '' && errorText}
          />
        )}
      />

The issue I'm facing is that the 'ref' attribute doesn't work as intended, according to examples in react-hook-form.

When I try to use 'inputRef' instead, I encounter TypeScript errors:

Property 'inputRef' does not exist on type 'DetailedHTMLProps<InputHTMLAttributes, HTMLInputElement>'

My attempt to add this 'inputRef' property to the index.d.ts file causes conflicts with other declared modules.

declare module 'react' {
  import React from 'react';

  interface HTMLInputAttributes<T> extends React.HTMLAttributes<T> {
    // extending React's HTMLAttributes
    inputRef?: any;
  }
}

declare module '*.svg' {
  const content: any;
  export const ReactComponent: any;
  export default content;
}

Answer №1

Instead of placing the reference on the Controller, it should have actually been placed in the input itself. Here is the corrected solution:

      <Controller
        control={control}
        name={name}
        render={props => (
          <input
            name={props.name}
            defaultValue={defaultValue}
            ref={register({
              validate
            })}
            type={'text'}
            placeholder={label}
            aria-label={label}
            onChange={handleChange}
            data-error={errorText !== '' && errorText}
          />
        )}

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

Using Typescript to define custom PopperComponent props in Material UI

I'm currently utilizing the Material UI autocomplete feature in my React and Typescript application. I'm looking to create a custom popper component to ensure that the popper is full-width. Here's how I can achieve this: const CustomPopper ...

An issue has occurred: the property 'map' cannot be read as it is undefined

Encountered this unexpected error and struggling to understand the reason behind it.. I've been attempting to showcase events on angular-calendar: Error occurred in error_handler.ts:1 - ERROR TypeError: Cannot read property 'map' of unde ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

The Type X is lacking essential properties found in Type Y, including length, pop, push, concat, and an additional 26 more properties. Code: [2740]

One interesting thing I have noticed is the Product interface: export interface Product{ code: string; description: string; type: string; } There is a service with a method that calls the product endpoint: public getProducts(): Observable<Product ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

What is the process for configuring PhpStorm to sync with TypeScript tsconfig.json in .vue files?

Vue.js (webpack + vueify) with TypeScript is my current setup. The ts configuration appears to be functioning, but only in .ts files. For instance, in tsconfig.json: "compilerOptions": { "strictNullChecks": false, So strictNullChecks works as expect ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

Checking links stored in an array using JavaScript

I am currently working on a JavaScript function that will iterate through an array of URLs to find a 'pingable' URL and return its index. Here is the code snippet I have so far: function ping(url: string): Promise { return new Promise((resolve) ...

Error: Unexpected token 'export' in NextJS Syntax

A situation has arisen where a library that was functioning perfectly in an app utilizing react-create-app is now needed for use in NextJS (using npx create-next-app --ts). However, upon attempting to integrate the library, an error was encountered: erro ...

react-hook-form encountered an error: TypeError - target.addObserver function does not exist

After creating a react application using create-react-app and integrating react-hook-form along with xmldom-ts, I encountered the following error: TypeError: target.addObserver is not a function MutationObserverImpl.observe I have provided a Codesanbox ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Exploring the contrasts and practical applications of Virtual Scroll versus Infinite Scroll within the framework of Ionic 3

After thoroughly reviewing the documentation for Ionic 3, I embarked on a quest to discern the disparity between https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/ and https://ionicframework.com/docs/api/components/infinite-scr ...

Specifying data types for keys within a generic parameter that is inferred

Objective I am currently developing a utility with the following interface: interface F<M extends Record<string, Function>> { ( listeners: M, options: { filter: e => boolean } ): void } An important aspect here is the filter o ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

The type 'ssr' is not found within the 'ResourcesConfig | LegacyConfig | AmplifyOutputs' interface. Error code: ts(2353)

I've been following a step-by-step tutorial (check it out here at 2:25:16) on creating a full stack application, but I've hit a roadblock when trying to enable SSR. import "@/styles/globals.css"; import type { AppProps } from "next ...

Content not displaying in Angular Material Tab (mat-tab)

Incorporating Angular Material tabs into my Angular 5 project has been quite the challenge. I am attempting to use the tabs as a submenu on a links page, where numerous links are categorized into smaller sections that will be displayed when selected from t ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

Mastering the Correct Usage of AuthGuard

I am facing an issue with implementing authguard in my angular application. I have set up a post request to my spring boot backend, and upon success, I set a value to true which I then check in my canActivate method of the authguard. However, for some reas ...

Error encountered when attempting to modify an Angular expression within a table that is being edited inline

In my table, there is a child component called modal which contains two buttons - save and cancel for inline editing. I am aware that I need to utilize "ChangeDetectorRef", but I am struggling to implement the event "ngAfterViewInit" in my code. An erro ...