I am trying to implement the following (simplified version of my) code:
import React, { ReactElement } from 'react';
import { LegacyRef } from 'react';
export interface TestProps<T> {
inputRef?: LegacyRef<T>;
multiline?: boolean;
}
export const Test = <T,>({ inputRef, multiline }: TestProps<T>): ReactElement | null => (
<>{multiline ? <textarea ref={inputRef} /> : <input ref={inputRef} type="text" />}</>
);
Here I want to be able to have two differing types of input shown depending on the multiline prop value. My plan was to do this using ts generics, passing the type of input (HTMLTextAreaElement or HTMLInputElement) when calling the component.
However, I can't seem to be able to get the transpiler to understand that the inputRef can take on more than one form, depending on what value is passed as a prop. I tried implementing the solutions provided on this thread as you can see in my code.
But I keep getting these errors on each respective ref
line:
Type 'LegacyRef<T>' is not assignable to type 'LegacyRef<HTMLTextAreaElement>'
Type 'LegacyRef<T>' is not assignable to type 'LegacyRef<HTMLInputElement>'
Does anyone know of a solution to this particular problem?
Any help would be greatly appreciated, thank you.