Search⌘ K
AI Features

Polymorphic Component Element Attributes

Explore how to build polymorphic React components that support element-specific attributes correctly. Understand the limitations of naive implementations and learn how TypeScript helps enforce type safety, preventing invalid HTML and improving developer experience during development and build time.

Introduction

Let's consider the current simple implementation again:

TypeScript 3.3.4
import React from "react";
export const PolymorphicText = ({ as, children }) => {
const Component = as || "span";
return <Component>{children}</Component>;
};

The only props this component accepts are as and children, and nothing else.

Javascript (babel-node)
const PolymorphicText = ({ as, children }) => {
...
};

There’s no attribute support taken into consideration here. For example, if as were the anchor element a, a consumer should also be able to pass href to the component.

TypeScript 3.3.4
<PolymorphicText as="a" href="https://www.example.com"> Link </PolymorphicText>
...