2

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;

1

1 Answer 1

4

React.forwardedRef expects you to provide a type for the returned element and the props in cases where it cannot be inferred. You can indicate it like this:

import * as React from "react";

interface Props {
  isLink?: boolean;
}

const Block = React.forwardRef<HTMLAnchorElement & HTMLDivElement, Props>(
  ({ isLink = false }, ref) => {
    return isLink ? (
      <a ref={ref} href="#nothing">
        {"I'm a link!"}
      </a>
    ) : (
      <div ref={ref}>{"I'm a div!"}</div>
    );
  }
);

export default Block;

The forwardRef type definition looks like this:

function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! this is working. Can you explain this a little bit more, please? why would I combine the types of HTMLAnchorELEment and HTMLDivElement when my component only returns one of them? why it shouldn't be HTMLAnchorElement | HTMLDivElement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.