Type alias PolymorphicComponentWithRef<Default>

PolymorphicComponentWithRef<Default>: (<As>(props: PolymorphicPropsWithRef<As>) => React.ReactElement | null)

Type Parameters

Type Parameters

  • Default extends React.ElementType

    The default element type used in the component (e.g. "div")

Type declaration

    • <As>(props: PolymorphicPropsWithRef<As>): React.ReactElement | null
    • Component that can be polymorphic and handle as-prop and ref

      Components, that are only used as layout component or not necessarily need to be a specific element, could be polymorphic. Types for these components are a bit more complicated. So here is an example of how to handle polymorphic as-prop in react components.

      Example

      import { forwardRef } from "react";
      import type { ElementType } from "react";
      import type {
      PolymorphicComponentWithRef,
      PolymorphicProps,
      PolymorphicRef
      } from "@dnshpf/ts-utils";

      const Box: PolymorphicComponentWithRef<"div"> = forwardRef(
      <As extends React.ElementType = "div">(
      { as: As, ...props }: PolymorphicProps<As>,
      ref: PolymorphicRef<As>
      ) => {
      const Element = As || "div";
      return <Element {...props} ref={ref} />;
      }
      );

      Type Parameters

      Type Parameters

      • As extends React.ElementType = Default

      Parameters

      Returns React.ReactElement | null

Generated using TypeDoc