Hi folks, today I would like to share a tip on how to keep your TailwindCSS DRY ("Don't Repeat Yourself"). One way we can do this is by extracting component classes to be used across our repeating elements. (Another way is by creating template partials or javascript components, but that's a whole other post in and of itself). For now, we will focus on the former.
First step is to have a style.css file in the src folder at the root of your project. Inside style.css, we will have the following code:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
}
Inside the curly braces is where we'll write our new utility components. In this instance we'll be making a button as an example.
We'll call it simply "btn". We are going to use @layer components directive to tell Tailwind what layer those styles belong to, and to instruct Tailwind to consider those styles for purging the components layer.
We are going to use standard tailwind utility classes to define the style of our button.
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn {
@apply w-48 px-4 py-2 text-lg font-medium tracking-wider text-white transition ease-in-out bg-teal-500 shadow-md rounded-3xl hover:bg-teal-400 hover:scale-105;
}
}
Import the style.css file at the top level of our app, and we can use our new "btn" utility for all the buttons in our project, with the following JSX:
<button className="btn">Click Me</button>
or HTML:
<button class="btn">Click Me</button>
This makes for much cleaner looking code, and helps to maintain a good level of uniformity throughout our project.
I hope you enjoyed reading this article, and that it helps you to simplify the process of extracting component classes and keeping your code nice and DRY.
Thanks for reading, happy coding!
Top comments (5)
Thanks for sharing this awesome tip!
My pleasure!
Havk you heard of daisyui.com/ ?
Not before reading your comment, but I am interested and will explore further. Thanks!
It might be a bit overkill for some.
But for those who just want an alternative to bootstrap, with the tailwind classes, it's great.