Search code examples
typescriptreact-hook-formreact-forwardref

react-hook-form and typescript - property 'inputRef' does not exist on type DetailedHTMLProps


This is my react-hook - controller

      <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 problem is ref does not work. It needs to be inputRef - as determined by react-hook-form examples. If I use inputRef, I get typescript errors:

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

If I try to add that property to the index.d.ts file it breaks all my other declared modules ..

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

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

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


Solution

  • I had put the ref on the Controller, when it should have been in the input itself. fix:

          <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}
              />
            )}