I have a Block component which will render a div or a tag based on a prop value. I want to pass a ref from the parent component to this component. Therefore, I need to use RefForwardingComponent type for my component variable type, but I get an error for type incompatibility between HTMLAnchorElement and HTMLDivElement. How can I fix it? here's the component code on CodeSandBox:
import * as React from "react";
interface Props {
isLink: boolean;
}
type PropsWithElementProps<T> = React.HTMLProps<T> & Props;
type RefComponent<T, U> =
| React.RefForwardingComponent<T, PropsWithElementProps<T>>
| React.RefForwardingComponent<U, PropsWithElementProps<U>>;
// error for Block variable type... full error on CodeSandBox link
const Block: RefComponent<HTMLAnchorElement, HTMLDivElement> = React.forwardRef(
({ isLink }, ref) => {
if (isLink)
return (
<a ref={ref} href="#nothing">
I'm a link!
</a>
);
else return <div ref={ref}>I'm a div!</div>;
}
);
export default Block;