Sub topic 3
When Loops and Multi-Cursor Editing Are Enough
This chapter assumes you know Tailwind utility classes such as flex, px-4, and bg-blue-600. It also assumes you can read a basic component or template, such as a React component, a Vue single-file component, or a server-side partial. It does not use @apply yet. The goal is to learn when you don't need a new abstraction.
Repeated text is not always repeated definition
A long class list that appears many times in rendered HTML is not automatically a problem. What matters is how many places in your source code define it.
- Repeated in output, defined once. A loop renders ten identical cards from one template. The class list exists once in your source. Changing it is a one-line edit.
- Repeated in source. You paste the same class list into ten places. Changing the design means finding and editing every copy, and missing one creates drift.
Reuse techniques only matter for the second case. Many "Tailwind has too much duplication" complaints come from the first case, where a loop already solves the problem.
Loops: one definition, many elements
If the repeated elements sit next to each other and differ only in their data, render them from an array. The class list is written once.
const actions = [
{ id: "save", label: "Save" },
{ id: "publish", label: "Publish" },
{ id: "send", label: "Send" },
];
export function Toolbar() {
return (
<div className="flex gap-2">
{actions.map((action) => (
<button
key={action.id}
className="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
>
{action.label}
</button>
))}
</div>
);
}The three buttons from the earlier duplication example are now one <button> element in the source. Adding a fourth action means adding one object to the array.
The same idea works in other template systems. In Vue:
<script setup>
const actions = ["Save", "Publish", "Send"];
</script>
<template>
<div class="flex gap-2">
<button
v-for="label in actions"
:key="label"
class="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
>
{{ label }}
</button>
</div>
</template>In a server-side template such as Jinja:
<div class="flex gap-2">
{% for label in ["Save", "Publish", "Send"] %}
<button class="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700">
{{ label }}
</button>
{% endfor %}
</div>Letting each item carry its own classes
Sometimes items in a loop differ in style. Store the complete class strings in the data, not fragments to be assembled.
const statuses = [
{ id: 1, label: "Active", classes: "bg-green-100 text-green-800" },
{ id: 2, label: "Pending", classes: "bg-yellow-100 text-yellow-800" },
{ id: 3, label: "Failed", classes: "bg-red-100 text-red-800" },
];
export function StatusList() {
return (
<ul className="flex gap-2">
{statuses.map((status) => (
<li
key={status.id}
className={`rounded-full px-3 py-1 text-sm font-medium ${status.classes}`}
>
{status.label}
</li>
))}
</ul>
);
}The shared classes are written once in the template. The per-item classes are written once each, in the data.
The class detection rule
Tailwind finds classes by scanning your source files as plain text. It does not run your code. A class is generated only if its complete name appears somewhere as an unbroken string.
This is the most common error when combining loops with Tailwind:
const colors = ["green", "yellow", "red"];
// Broken: Tailwind never sees "bg-green-100" as a complete string.
const badges = colors.map((color) => (
<span key={color} className={`bg-${color}-100 text-${color}-800`}>
{color}
</span>
));The source text contains bg-${color}-100, which is not a class name. The page renders with no background color, and no error is reported. Fix it with a lookup that holds whole class names:
const colorClasses = {
green: "bg-green-100 text-green-800",
yellow: "bg-yellow-100 text-yellow-800",
red: "bg-red-100 text-red-800",
};
const badges = Object.keys(colorClasses).map((color) => (
<span key={color} className={colorClasses[color]}>
{color}
</span>
));Multi-cursor and find-and-replace editing
Sometimes the repeated elements cannot be put in a loop. They may be different elements with different content and structure, such as three different buttons in three different parts of one page. Here the class list really is typed multiple times.
If the copies live in one file and you will rarely change them, your editor can do the maintenance. Most editors can edit all copies at once:
- Select next occurrence. In VS Code,
Ctrl+D(Cmd+Don macOS) adds the next match of the selected text as another cursor. - Select all occurrences.
Ctrl+Shift+L(Cmd+Shift+L) puts a cursor on every match in the file. - Find and replace.
Ctrl+H(Cmd+Option+F) replaces text across the file, and the search-in-files panel does it across the project.
For example, to change a button from blue to indigo, select bg-blue-600 hover:bg-blue-700, press the select-all shortcut, and type the replacement. All copies change in one step.
This works only when the copies stay textually identical. A class-sorting tool such as prettier-plugin-tailwindcss helps, because it puts utilities in a fixed order. Without sorting, px-4 py-2 rounded-md and rounded-md px-4 py-2 mean the same thing but do not match as text.
Why this approach has limits
Multi-cursor editing is a way to maintain duplication, not remove it. It has these weaknesses:
- It depends on a human noticing. Nothing tells a new teammate that a class list is copied in six files.
- Copies drift. One copy gets
focus:ring-2during a bug fix and the others don't. - It stops at the file boundary in practice. Project-wide replace works, but it also matches things you did not mean to change, so you review every hit.
- It cannot express intent. The code does not say "this is the primary button," so nobody knows which similar-looking copies should change together.
Choosing between the options in this chapter
The deciding question is whether the repeated elements should always change together.
| Situation | Best fit | Reason |
|---|---|---|
| Menu items, table rows, cards from a data list | Loop | One element in source, no abstraction needed |
| Three one-off buttons in a single landing page | Multi-cursor editing | Low change rate, no need for a new name |
| Same button on many pages | Component or partial | Change once, update everywhere |
| Same class list with different structure inside | Component with slots or children | A loop cannot vary the markup |
| Repeated across files and teams | Component or shared class | Needs a single owner and a name |
Later chapters cover the "component" rows in detail. For now, the rule is: try the lightest option that keeps each design decision in one place.
Common errors
- Building class names dynamically. As shown above,
bg-${color}-500produces no CSS. Use full strings in a lookup. - Looping where the markup differs. If each item needs different child elements, a loop with many
ifbranches becomes harder to read than separate elements. Consider a component instead. - Forgetting the
keyprop. In React and Vue loops, each item needs a stablekey. A missing key causes console warnings and odd update behavior. - Using multi-cursor on unsorted classes. Two copies that differ only in order will not match. Sort classes first, or search for one class at a time.
- Replacing too widely. Replacing
p-4across the whole project also hitslg:p-4andhover:p-4. Search with enough context, and review each match. - Treating a loop as a component. A loop shares markup only inside one template. If the same list appears on two pages, the markup is again defined twice.
What you can rely on
- Duplication in rendered HTML is acceptable. Duplication in source is what costs you.
- Loops remove source duplication for adjacent, data-driven elements.
- Editor tools reduce the cost of edits but leave the duplication in place.
- Tailwind reads class names as plain text, so every class must be written out in full.
Exercise
A teammate writes a list of status badges with className={bg-${status.color}-100}, where status.color is "green", "yellow", or "red". The badges render with no background. Why, and how do you fix it?
Show answer
Tailwind scans source files as plain text and never evaluates the template string, so it never sees bg-green-100, bg-yellow-100, or bg-red-100 as complete class names and generates no CSS for them. Fix it by writing each full class name in the source, for example a lookup object such as { green: "bg-green-100", yellow: "bg-yellow-100", red: "bg-red-100" }, and reading colorClasses[status.color].
Exercise
A page has a row of five "Download" links that share one class list and differ only by file name and URL. Which technique fits, and what changes if the same row must also appear on three other pages?
Show answer
A loop over an array of { name, url } objects fits, because the elements are adjacent and differ only by data, so the class list is written once. If the row must appear on three other pages, the loop's markup would be defined once per page. Extract a component or partial so that all four pages share one definition.