Note: fork of the original library, makes the following changes:
- Publishes the package under
sixfoldscope in a private registry.- Fixes the return type: kripod#13
Zero-runtime polymorphic component definitions for React
Being a successor to react-polymorphic-box, this project offers more accurate typings with less overhead.
- Automatic code completion, based on the value of the
asprop - Static type checking against the associated component’s inferred props
- HTML element name validation
A Heading component can demonstrate the effectiveness of polymorphism:
<Headingcolor="rebeccapurple">Heading</Heading><Headingas="h3">Subheading</Heading>Custom components like the previous one may utilize the package as shown below.
importtype{PolymorphicPropsWithoutRef}from"react-polymorphic-types";// An HTML tag or a different React component can be rendered by defaultexportconstHeadingDefaultElement="h2";// Component-specific props should be specified separatelyexporttypeHeadingOwnProps={color?: string;};// Extend own props with others inherited from the underlying element type// Own props take precedence over the inherited onesexporttypeHeadingProps<TextendsReact.ElementType=typeofHeadingDefaultElement>=PolymorphicPropsWithoutRef<HeadingOwnProps,T>;exportfunctionHeading<TextendsReact.ElementType=typeofHeadingDefaultElement>({ as, color, style, ...restProps}: HeadingProps<T>){constElement: React.ElementType=as||HeadingDefaultElement;return<Elementstyle={{ color, ...style}}{...restProps}/>;}With React.forwardRef
import*asReactfrom"react";importtype{PolymorphicForwardRefExoticComponent,PolymorphicPropsWithoutRef,PolymorphicPropsWithRef}from"react-polymorphic-types";import{HeadingDefaultElement,HeadingOwnProps}from"./Heading";exporttypeHeadingProps<TextendsReact.ElementType=typeofHeadingDefaultElement>=PolymorphicPropsWithRef<HeadingOwnProps,T>;exportconstHeading: PolymorphicForwardRefExoticComponent<HeadingOwnProps,typeofHeadingDefaultElement>=React.forwardRef(functionHeading<TextendsReact.ElementType=typeofHeadingDefaultElement>({
as,
color,
style,
...restProps}: PolymorphicPropsWithoutRef<HeadingOwnProps,T>,ref: React.ForwardedRef<Element>){constElement: React.ElementType=as||HeadingDefaultElement;return<Elementref={ref}style={{ color, ...style}}{...restProps}/>;});With React.memo
import*asReactfrom"react";importtype{PolymorphicMemoExoticComponent}from"react-polymorphic-types";import{Heading,HeadingDefaultElement,HeadingOwnProps}from"./Heading";exportconstMemoizedHeading: PolymorphicMemoExoticComponent<HeadingOwnProps,typeofHeadingDefaultElement>=React.memo(Heading);With React.lazy
import*asReactfrom"react";importtype{PolymorphicLazyExoticComponent}from"react-polymorphic-types";importtype{HeadingDefaultElement,HeadingOwnProps}from"./Heading";exportconstLazyHeading: PolymorphicLazyExoticComponent<HeadingOwnProps,typeofHeadingDefaultElement>=React.lazy(async()=>{const{ Heading }=awaitimport("./Heading");return{default: Heading};});