161 days ago · Tech · hide · Fediverse post

While working on the design system at Duna, I faced some difficulties trying to make a component polymorphic while also preserving type safety. Here is a short article to share what I learned. Starting with an example Consider a Text component which renders a piece of text on screen, using one or more class names to carry its styles (could be normal CSS or Tailwind or whatever). Now, we don’t want to force a specific HTML element for that, because there are plenty of use cases we want to support: it could be a paragraph, a link, a span, a figcaption, you name it. So we allow passing the element to render with the as prop, and default to span. function Text({ as: As, children, ...props }) { const Component = As ?? 'span' return ( <Component {...props} className="some class names"> {children} </Component> ) } Some elements though need or want additional attributes. For instance, a <a> needs href, a <time> needs datetime, a <data> needs value, and so on. That’s why we accept arbitrary…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town