Extracting Reusable Components with Tailwind
While Tailwind CSS encourages utility-first development, it's common to reuse combinations of utility classes across components. Instead of repeating long class lists, you can extract them into reusable components using @apply
, partials, or components in your JS/Blade/Vue/React templates.
1. Using @apply
in Custom CSS
Define a class in your custom CSS file and apply commonly used utility combinations with @apply
:
/* styles.css */
.btn {
@apply px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700;
}
.card {
@apply shadow-md rounded-lg p-6 bg-white;
}
2. HTML/Blade/React Component Extraction
In templating engines like Blade, or frameworks like React, Vue, or Alpine, it's common to extract components:
<button {{ $attributes->merge(['class' => 'btn']) }}>
{{ $slot }}
</button>
<x-button>Click Me</x-button>
3. React/JSX Component
function Button({ children }) {
return (
<button className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
{children}
</button>
);
}
4. Why Reuse Matters
- Reduces duplication of utility classes.
- Makes your components easier to read and maintain.
- Encourages design consistency across your UI.
- Improves productivity when working in teams or large projects.
Conclusion
You donβt have to choose between utility-first and component-based design β Tailwind enables both. Extract reusable components with @apply
or templates, and speed up your UI workflow without sacrificing structure or consistency.