Lesson 9 of 11Article14 min
Reusable Components & @apply
Repeat the same utility combination 3+ times? Extract a React component or use @apply in CSS for a semantic class name.
When to extract components
Repeat the same utility combination 3+ times? Extract a React component or use @apply in CSS for a semantic class name.
React component vs @apply
// Preferred: React component
function Button({ children, variant = "primary" }) {
const base = "rounded-xl px-4 py-2 font-semibold transition";
const styles = {
primary: "bg-cyan-500 text-white hover:bg-cyan-600",
ghost: "border border-slate-200 hover:bg-slate-50",
};
return <button className={`${base} ${styles[variant]}`}>{children}</button>;
}@apply in CSS (use sparingly)
@layer components {
.btn-primary {
@apply rounded-xl bg-cyan-500 px-4 py-2 font-semibold text-white
hover:bg-cyan-600 transition;
}
}