How to use React.forwardRef with TypeScript when using different html elements in the render

Viewed 3013

I am struggling with that very simple component that displays a span or a <br> depending on the props:

import * as React from 'react';

type Props = {value: string}

function LetterRenderer({value = ''}: Props, ref: React.Ref<HTMLElement>) {
    switch(value) {
      case '\n': return (<br ref={ref} />);
      default: return (<span ref={ref}>{value}</span>);
    }
}

const Letter = React.forwardRef<HTMLElement, Props>(LetterRenderer);
Letter.displayName = 'Letter';
export default Letter;

On <br ref={ref} />, the second ref is underlined with the following error message:

Type 'Ref<HTMLElement>' is not assignable to type 'string | ((instance: HTMLBRElement | null) => void) | RefObject<HTMLBRElement> | null | undefined'.
  Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLBRElement | null) => void) | RefObject<HTMLBRElement> | null | undefined'.
    Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLBRElement>'.
      Property 'clear' is missing in type 'HTMLElement' but required in type 'HTMLBRElement'.ts(2322)
lib.dom.d.ts(6336, 5): 'clear' is declared here.
index.d.ts(106, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLBRElement>, HTMLBRElement>'

How should I work around this?

1 Answers
function LetterRenderer({value = ''}: Props, ref: React.Ref<HTMLElement>) {
// ...

Your ref prop accepts HTMLElement but what you really want is HTMLBRElement | HTMLSpanElement because ref is passed into a <br> and <span> who's ref attribute is React.Ref<HTMLBRElement> and React.Ref<HTMLSpanElement> respectively.

Change the ref prop to

ref: React.Ref<HTMLBRElement | HTMLSpanElement>

Note that HTMLBRElement and HTMLSpanElement both inherit HTMLElement but not the other way around; HTMLElement does not have clear attribute but HTMLBRElement does.

Update:

Because <br>'s and <span>'s ref attribute accepts only React.Ref<HTMLBRElement> and React.Ref<HTMLSpanElement> respectively, ref needs to be casted inline accordingly.

<br ref={ref as React.Ref<HTMLBRElement>} />

<span ref={ref as React.Ref<HTMLSpanElement>}>{text}</span>
Related