Typed Tailwind Styling for Multi-Part Components
Complex components such as dialogs and menus can be challenging to style because they are made up of many parts. For example, a dialog might include a header, body, and footer.
Applying base styles is straightforward, but how can one create an error variant with a red header? Or override the body padding for a specific instance?
Let's explore a pattern that addresses these questions and improves the developer experience at the same time.
Separation of style and state
Before we get started, let’s agree on a few basic principles:
Following these principles, we can:
Implementing this pattern
Let’s apply this pattern in practice! This guide assumes you’re using React and Tailwind.
Install Tailwind Variants
Tailwind Variants is an excellent variant API with support for slots.
Define utility types and functions
Add the following wherever you keep your utility functions.
Set up Tailwind VSCode Intellisense
Add the following to your workspace settings file (*.code-workspace).
Using this pattern in your components
Import your dependencies
Create a Tailwind Variants object
Add the styles for each part of your component to slots (See the Tailwind Variant docs for more details).
Extend your component props
Consume the generated styles
Use your new component
Full code example
You can play with a full code example here: https://codesandbox.io/s/tailwind-classnames-d8n6rp.
It only takes a small amount of setup to combine TypeScript and Tailwind to style complex components.
Here at Polytomic we’ve found it beneficial to use Tailwind Variants even for smaller components. It’s a simple pattern that promotes a clear separation of concerns.
Comments welcome on Hacker News!