react-polymorphic-box
Building blocks for strongly typed polymorphic components in React.
? Motivation
Popularized by Styled Components v4, the as
prop allows changing the HTML tag rendered by a component, e.g.:
While this pattern has been encouraged by several libraries, typings had lacked support for polymorphism, missing benefits like:
- Automatic code completion, based on the value of the
as
prop - Static type checking against the associated component's inferred props
- HTML element name validation
? Usage
A Heading
component can demonstrate the effectiveness of polymorphism:
Custom components like the previous one may utilize the package as shown below.
Forwarding Refs
Library authors should consider encapsulating reusable components, passing a ref through each of them: