2 hours ago · Tech · 0 comments

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…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.