Atomic Design for React components using Tailwind classes
I was thinking about basing my app's components on atomic design since I like the approach: "a component defines how it can look, the implementation just says where it goes".
This basically means:
- CSS Props like "margin", "position" and "z-index" may not be defined on a component's root level element within that component itself, but instead in the implementation
- Other props like "color" are defined within the component and can be made changeable by custom props like e.g. "variant"
This sounds nice but is hard to enforce since I usually style my components by simply passing "classNames" to it containing Tailwind classes, and I could potentially also pass classNames like "bg-red-500" which is something I don't want.
Is there any common way to do this easily?
Probably the way with the best DX would be a VS Code extension like "Tailwind CSS IntelliSense" which gives us auto-complete in the classNames prop of a component.
Apart from that I thought about writing a custom type for my components, based on
React.FC
and extending it by margin, position, etc. instead of passing "classNames" as a prop in every component, but then I need a complex api that can handle everything from m-1
to mx-2 -ml-[calc(100px-2rem)]
which sounds like a nightmare to me (also having in mind tailwind's tree-shaking)
Did anyone of you ever waste a thought on this or has an opinion on the whole thing?
Good idea? Bad idea? Good idea but too hard to make accessible?3 Replies
a common way of doing a "base component" with tailwind is like this
GitHub
ui/apps/www/components/ui/button.tsx at main · shadcn/ui
Beautifully designed components built with Radix UI and Tailwind CSS. - ui/apps/www/components/ui/button.tsx at main · shadcn/ui
you give the minimum styling necessary and who is using the app deal with the rest
if you are building a public component library, then you can make a more strict rule about it
but if its for internal usage only, just assume that things will work as they should