javascriptreactjstypescripttypesreact-select

Type 'ForwardedRef<HTMLInputElement>' is not assignable to type 'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'. in react-select


I am getting this TypeScript error when I use forwardRef in my Select component while using react-select.

Type 'ForwardedRef<HTMLInputElement>' is not assignable to type
'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.
import Select from "react-select";

export const SelectInput = forwardRef<HTMLInputElement, SelectInputProps>(
 (props, ref) =>{
    ...

    return(
     <div>
       <Select
         key="random-key"
         ref={ref}
         ....
        />
     </div>
    )
 }
)

I used the same type and forwardRef with an input element and everything seems to be fine but I having issues here. I have tried several solution such as this one useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement> it didn't work for me.

This is a full log of the error

Type 'ForwardedRef<HTMLInputElement>' is not assignable to type 'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.

Type '(instance: HTMLInputElement | null) => void' is not assignable to type 'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.
    Type '(instance: HTMLInputElement | null) => void' is not assignable to type '(instance: Select<Option, false, GroupBase<Option>> | null) => void | (() => VoidOrUndefinedOnly)'.
      Types of parameters 'instance' and 'instance' are incompatible.
        Type 'Select<Option, false, GroupBase<Option>> | null' is not assignable to type 'HTMLInputElement | null'.
          Type 'Select<Option, false, GroupBase<Option>>' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 352 more.

Solution

  • The issue arises because the ref you are forwarding is of type HTMLInputElement, but the ref for the react-select component expects a type that aligns with its internal Select component, not a DOM HTMLInputElement.

    You need to adjust the ref type to match what react-select expects. react-select uses a custom Select component and not a native HTML input, so you must forward the ref with the correct type.

    Do this:

    import React, { forwardRef } from "react";
    import Select, { GroupBase, Props as SelectProps } from "react-select";
    
    interface Option {
      label: string;
      value: string;
    }
    
    interface SelectInputProps extends SelectProps<Option, false, GroupBase<Option>> {
      // You can extend or add custom props here if needed
    }
    
    export const SelectInput = forwardRef<Select<Option, false, GroupBase<Option>>, SelectInputProps>(
      (props, ref) => {
        return (
          <div>
            <Select
              {...props}
              ref={ref}
            />
          </div>
        );
      }
    );