Type 'MutableRefObject<ForwardRefExoticComponent<TextInputProps & RefAttributes<TextInput>> | null>' is not assignable to type 'Ref<TextInput> | undef

Viewed 1018

I get the following error when passing a ref to a <TextInput>in React Native:

Type 'MutableRefObject<ForwardRefExoticComponent<TextInputProps & RefAttributes> | null>' is not assignable to type 'Ref | undefined'. Type 'MutableRefObject<ForwardRefExoticComponent<TextInputProps & RefAttributes> | null>' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'ForwardRefExoticComponent<TextInputProps & RefAttributes> | null' is not assignable to type 'TextInput | null'. Type 'ForwardRefExoticComponent<TextInputProps & RefAttributes>' is missing the following properties from type 'TextInput': isFocused, clear, measure, measureInWindow, and 19 more.ts(2322) index.d.ts(140, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & TextInputProps & RefAttributes'

Here is my code:

    const useInputRef = () => useRef<typeof TextInput | null>(null);
    const inputRefs = Array.from({ length: numberOfInputs }, useInputRef);
...
            <TextInput
                ref={inputRefs[index]} // error here    

How can I pass the ref to the TextInput with out error?

1 Answers

Solved by replacing useInputRef:

const useInputRef: InputRefType = () => useRef(null);

and then

export type InputRefType = () => React.MutableRefObject<TextInputRefType | null>;

export type TextInputRefType = TextInput;

Related