Using Tailwind like styled-components
Gerrit Weiermann
Posted on August 31, 2021
Introduction
It is time to learn something new. Yesterday I watched fireships video about TailwindCSS that motivated me to give it a try. Initially, I didn't like it much, because of readability and learning (kind of) a new language.
So I started creating my first button component in React.
With the knowledge I would want to create many more, I quickly missed the easy way I'd create components with styled-components.
I got carried away and made myself a version of styled-components. With the difference that it would just take class names as arguments:
The Tailwind like styled-components
(or however you want to call it).
The development was quite straightforward. But I also wanted to use typescript.
Finding the correct typings took me a long while to accomplish. After all, I finally did finish my prototype. Here's how to use it:
export const Button = tailwind.button`px-2 py-1 m-5 bg-green-500 rounded-md`
And I thought it would be also useful to have a set of different stylings you could combine, so I implemented the following as well:
const spacing = "px-2 py-1 m-5"
const primary = "bg-red-500"
const rounded = "rounded-md"
export const Button = tailwind_fn.button(spacing, primary, rounded)
Now I'm proud of it and forgot about my previous goal: learning tailwind (lol)
If you are interested in the source code, I uploaded it to pastebin (not github because I'm very lazy :))
It's just 50 lines of code!
It was already there
Also: After doing research I found out this was possible before (obviously), with actually using styled-components itself:
An Efficient React + TailwindCSS + Styled Components Workflow
Derek Shanks ・ Jan 22 '20 ・ 6 min read
That's it
Thank's for reading and have a nice day :D
Share your thoughts on this if you like :)
Posted on August 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 18, 2023