Skip to content

Repository files navigation

react-polymorphic-box

Building blocks for strongly typed polymorphic components in React.

npmLanguage grade: JavaScriptTravis (.com)Commitizen friendly

Animated demonstration of package capabilities

💡 Motivation

Popularized by Styled Components v4, the as prop allows changing the HTML tag rendered by a component, e.g.:

import{Box}from'react-polymorphic-box';import{Link}from'react-router-dom';<Boxas="a"href="https://github.com/kripod">GitHub</Box><Boxas={Link}to="/about">About</Box>

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:

<Headingcolor="rebeccapurple">Heading</Heading><Headingas="h3">Subheading</Heading>

Custom components like the previous one may utilize the package as shown below.

import{Box,PolymorphicComponentProps}from"react-polymorphic-box";// Component-specific props should be specified separatelyexporttypeHeadingOwnProps={color?: string;};// Merge own props with others inherited from the underlying element typeexporttypeHeadingProps<EextendsReact.ElementType>=PolymorphicComponentProps<E,HeadingOwnProps>;// An HTML tag or a different React component can be rendered by defaultconstdefaultElement="h2";exportfunctionHeading<EextendsReact.ElementType=typeofdefaultElement>({
color,
style,
...restProps}: HeadingProps<E>): JSX.Element{// The `as` prop may be overridden by the passed propsreturn<Boxas={defaultElement}style={{ color, ...style}}{...restProps}/>;}

Typing external components

Alternatively, you can also type your custom components by using the PolymorphicComponent type. This is especially handy when working with external libraries that already expose polymorphic components. Here's an example implementing the Heading component from above using styled-components:

import{PolymorphicComponent}from"react-polymorphic-box";importstyledfrom"styled-components";// Component-specific propsexporttypeHeadingProps={color?: string;};// An HTML tag or a different React component can be rendered by defaultconstdefaultElement="h2";exportconstHeading: PolymorphicComponent<HeadingProps,// Merged with props from the underlying element typetypeofdefaultElement// Default element type (optional, defaults to 'div')>=styled(defaultElement)<HeadingProps>` color: ${(props)=>props.color};`;

Forwarding Refs

Library authors should consider encapsulating reusable components, passing a ref through each of them:

import{Box}from"react-polymorphic-box";exportconstHeading: <EextendsReact.ElementType=typeofdefaultElement>(props: HeadingProps<E>)=>React.ReactElement|null=React.forwardRef(<EextendsReact.ElementType=typeofdefaultElement>({ color, style, ...restProps}: HeadingProps<E>,ref: typeofrestProps.ref)=>{return(<Boxas={defaultElement}ref={ref}style={{ color, ...style}}{...restProps}/>);});

The component can then receive a ref prop (live demo), just like a regular HTML element:

import{useRef}from"react";functionApp(){constref=useRef<HTMLHeadingElement>(null);return<Headingref={ref}>It works!</Heading>;}

About

Building blocks for strongly typed polymorphic components in React.

Topics

Resources

Code of conduct

Contributing

Stars

346 stars

Watchers

5 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages