Tuesday, 11 April 2023

type for useRef on a dynamic component

To avoid code duplication. We use some of the dynamic tag approaches. Basically, we have a component like this

type NavUtilDropdownProps = {
  ...
  component?: keyof JSX.IntrinsicElements;
  ...
  children: React.ReactElement;
};
const NavUtilDropdown: FC<NavUtilDropdownProps> = (props) => {
  const ref = useRef<HTMLElement | null>(null);
  const {
    ...
    component: Component = 'div',
  }
  ....
  {/* the Component will be whatever string we pass in,such as div section or a */}
  return <Component ref={ref} />
}

However, I'm getting a couple of TypeScript errors.

First. TS2590: Expression produces a union type that is too complex to represent. I believe this is cause by the second error, which provides more information.

The second error is here.

Error:(163, 6) TS2322: Type '{ children: Element[]; ref: MutableRefObject<HTMLElement | null>; className: string; "data-testid": string; onMouseLeave: (event: MouseEvent<Element, MouseEvent>) => void; }' is not assignable to type 'SVGProps<SVGSymbolElement>'.
  Types of property 'ref' are incompatible.
    Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<SVGSymbolElement> | undefined'.
      Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'RefObject<SVGSymbolElement>'.
        Types of property 'current' are incompatible.
          Type 'HTMLElement | null' is not assignable to type 'SVGSymbolElement | null'.
            Type 'HTMLElement' is missing the following properties from type 'SVGSymbolElement': ownerSVGElement, viewportElement, correspondingElement, correspondingUseElement, and 2 more.

Minimal example:

import React, { FC, useRef } from 'react'

type NavUtilDropdownProps = {
  component?: keyof JSX.IntrinsicElements;
};

const NavUtilDropdown: FC<NavUtilDropdownProps> = ({component: Component}) => {
  const ref = useRef<HTMLElement | SVGSymbolElement | null>(null);
  if (!Component) return null
  
  return <Component ref={ref} /> // type errors
}

See playground



from type for useRef on a dynamic component

No comments:

Post a Comment