mr__brainwash
mr__brainwash

Reputation: 1382

ForwardRef type based on props

I am using React + Typescript. I am working on a component that can return dynamic HTML element depends on props:

interface Props {
  label?: string;
}

const DynamicComponent = forwardRef<
  HTMLButtonElement | HTMLLabelElement,
  Props
>((props, ref) => {
  if (props.label) {
    return (
      <label ref={ref as React.ForwardedRef<HTMLLabelElement>}>
        {props.label}
      </label>
    );
  }
  return (
    <button ref={ref as React.ForwardedRef<HTMLButtonElement>}>BUTTON</button>
  );
});

Is it possible to type ref's interface in a way that will depend on the label prop?

export default function App() {
  const btnRef = useRef<HTMLButtonElement>(null); // Allowed
  const labelRef = useRef<HTMLLabelElement>(null); // Allowed
 //  const labelRef = useRef<HTMLButtonElement>(null); // Not allowed, because `label` prop was not provided
  return (
    <>
      <DynamicComponent ref={btnRef} />
      <DynamicComponent ref={labelRef} label="my label" />
    </>
  );
}

Sandbox link

Upvotes: 2

Views: 2756

Answers (1)

In order to do that we need to use function overloading, with higher order function pattern and typeguards:

FIXED

import React, { forwardRef, useRef, Ref } from 'react'

interface Props {
  label?: string;
}

// typeguard
const isLabelRef = (props: Props, ref: React.ForwardedRef<any>): ref is React.ForwardedRef<HTMLLabelElement> => {
  return true // ! NON IMPLEMENTED
}

// typeguard
const isButtonRef = (props: Props, ref: React.ForwardedRef<any>): ref is React.ForwardedRef<HTMLButtonElement> => {
  return true // ! NON IMPLEMENTED
}

// Higher order COmponent with overloads
function DynamicComponent<T extends HTMLButtonElement>(reference: Ref<T>): any
function DynamicComponent<T extends HTMLLabelElement>(reference: Ref<T>, props: Props): any
function DynamicComponent<T extends HTMLElement>(reference: Ref<T> | undefined, props?: Props) {

  const WithRef = forwardRef<HTMLElement, Props>((_, ref) => {
    if (props && isLabelRef(props, ref)) {
      return (
        <label ref={ref}>
          {props.label}
        </label>
      );
    }

    if (props && isButtonRef(props, ref)) {
      return (
        <button ref={ref}>BUTTON</button>
      );
    }
    return null
  });

  return <WithRef ref={reference} />
}


export default function App() {
  const btnRef = useRef<HTMLButtonElement>(null); // Allowed
  const labelRef = useRef<HTMLLabelElement>(null); // Allowed

  return (
    <>
      {DynamicComponent(btnRef)}
      {DynamicComponent(labelRef, { label: 'sdf' })}
    </>
  );
}

Playground

As you might have noticed, I use only props from DynamicComponent.

Also T generic parameter serves for narrowing the ref type

I left isButtonRef and isLabelRef unimplemented

UPDATE Seems that my previous example is useless. Sorry for that.

My bad. I have already fixed it.

As an alternative solution, you can override built in forwardRef function.

interface Props {
  label: string;
}

declare module "react" {
  function forwardRef<T extends HTMLButtonElement, P>(
    render: ForwardRefRenderFunction<HTMLButtonElement, never>
  ): ForwardRefExoticComponent<
    PropsWithRef<{ some: number }> & RefAttributes<HTMLButtonElement>
  >;

  function forwardRef<T extends HTMLLabelElement, P extends { label: string }>(
    render: ForwardRefRenderFunction<HTMLLabelElement, { label: string }>
  ): ForwardRefExoticComponent<
    PropsWithRef<{ label: string }> & RefAttributes<HTMLLabelElement>
  >;
}

const WithLabelRef = forwardRef<HTMLLabelElement, Props>((props, ref) => (
  <label ref={ref}>{props.label}</label>
));

const WithButtonRef = forwardRef<HTMLButtonElement>((props, ref) => (
  <button ref={ref}>{props}</button>
));

function App() {
  const btnRef = useRef<HTMLButtonElement>(null);
  const labelRef = useRef<HTMLLabelElement>(null);
  const divRef = useRef<HTMLDivElement>(null);

  return (
    <>
      <WithButtonRef ref={btnRef} />
      <WithLabelRef ref={labelRef} label="my label" />
      <WithLabelRef ref={divRef} label="my label" /> //expected error
    </>
  );
}

Upvotes: 2

Related Questions