Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Components and Reuse

Reusing Styles with Components

Handle repeated Tailwind CSS class lists the right way: loops, partials, components, variant maps for buttons, and when copy-and-paste is actually fine.

The first complaint people have about utility classes is "my HTML is full of long class lists, and I repeat them". It is a fair worry. A button with ten classes appearing in forty places sounds like a maintenance problem. The answer is not to go back to hand-written CSS class names; it is to reuse at the template level, with the tools your language and framework already give you: loops, partials, components and functions.

This lesson shows why that works, how to build a component with variants, and the few cases where a CSS class is better.

Why repeated classes are less scary than they look

Duplication in CSS is a problem because the class .btn lives far from where it is used, and changing it affects unknown places. With utilities the styles live on the element, so:

  • Changing one element never breaks another.
  • You can see the whole style at the place you read.
  • The generated CSS does not grow when you repeat a class; px-4 is generated once.

So the real maintenance problem is not repeated classes, it is repeated markup. If the same card appears ten times, make it a component and the class list exists in exactly one place.

flowchart TD
  A["Same markup in many places?"] -->|"yes"| B["Make a template component<br/>(partial, Blade, JSX, web component)"]
  A -->|"no, just a long class list"| C["Leave it. Utilities live with the element"]
  B --> D{"Plain HTML, no template engine?"}
  D -->|"yes"| E["Small CSS class with @apply<br/>(next lesson)"]
  D -->|"no"| F["Pass props, map them to classes"]

Reuse where the markup repeats, not where the class names repeat.

Loops

When one block repeats because the data repeats (cards in a list, rows in a table), the loop is already your abstraction.

JS One template, many cards

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The class list is written once, in card. The same idea works in any stack: a @foreach in Blade, {items.map(...)} in JSX, v-for in Vue, {% for %} in Twig.

A component with variants

Real buttons come in sizes and colors. The classic mistake is building the class string with string concatenation like 'bg-' + color + '-500'. Tailwind finds class names by scanning your source for complete strings, so partial pieces are never detected in a build (see Arbitrary Values and Resolving Conflicts). The pattern that works is a lookup table of full class names.

A button function with variant and size maps

Every class appears as a whole word in the source, so a build can find them. The component's callers pass meaning (variant: 'danger'), not styling.

In a framework, the idea is identical. A Blade component might look like this (read-only):

HTML
{{-- resources/views/components/button.blade.php --}}
@props(['variant' => 'primary'])
@php
  $variants = [
    'primary' => 'bg-indigo-600 text-white hover:bg-indigo-500',
    'secondary' => 'bg-slate-100 text-slate-900 hover:bg-slate-200',
  ];
@endphp
<button {{ $attributes->class(['rounded-lg px-4 py-2 font-medium', $variants[$variant]]) }}>
  {{ $slot }}
</button>

And a React one:

JSX
const variants = {
  primary: 'bg-indigo-600 text-white hover:bg-indigo-500',
  secondary: 'bg-slate-100 text-slate-900 hover:bg-slate-200',
};

export function Button({ variant = 'primary', className = '', ...props }) {
  return <button className={`rounded-lg px-4 py-2 font-medium ${variants[variant]} ${className}`} {...props} />;
}

Libraries such as class-variance-authority and tailwind-merge (both optional) formalize this: the first builds class strings from variant definitions, the second resolves conflicts when a caller passes an extra className.

Editing many places at once

If you still have repeated markup in plain HTML, your editor helps:

  • Multi-cursor editing and project-wide search-and-replace change a class list in every occurrence.
  • Tailwind's official editor extensions (IntelliSense) autocomplete classes, show the CSS behind them and sort them automatically with the Prettier plugin prettier-plugin-tailwindcss, so lists stay consistent and diffs stay small.

When duplication is fine

If an element appears only twice, copying it is simpler than inventing an abstraction. A rule of thumb: extract a component when the same markup appears three or more times, or when the pieces must stay in sync (a button on every page). Do not extract a "Card" component after one use, because you do not yet know which parts vary.

When a CSS class is the right tool

Sometimes a utility list is the wrong place for the style:

  • Content you do not control: Markdown or CMS output where you cannot add classes. A rule like .prose h2 { @apply text-xl font-semibold; } styles it from outside (the official typography plugin does exactly this).
  • Third-party widgets that need CSS selectors.
  • A pseudo-element recipe so long it hides the markup.

For those, write a small class and use @apply, explained in Base and Component Layers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you remove duplication when the same card markup appears ten times?

    The duplication is in the markup, so the fix belongs in the template layer.
  2. 2. Why map variants to full class names in an object?

    Tailwind scans for whole tokens, so 'bg-' + color never matches any real class.
  3. 3. Which situation justifies a CSS class with @apply?

    When you cannot touch the markup, a selector-based rule is the practical tool.
  4. 4. What problem does tailwind-merge solve?

    When a component accepts extra classes, tailwind-merge keeps the last conflicting utility.

Summary

  • Repeated utility classes are not the problem; repeated markup is.
  • Fix repeated markup with loops, partials and components, and keep the class list in one place.
  • Use lookup tables of complete class names for variants and sizes; never build class names from fragments.
  • Use editor tooling and the Prettier plugin to keep class lists readable.
  • Reach for a CSS class only for content you cannot mark up or for selector-heavy cases.

Next: Base and Component Layers