Best practice-ek
Class sorrend, Prettier plugin, clsx, cn() helper, mikor bontsd komponensre.
Best practice-ek
1. Olvasható class lista
Rendezd a class-eket logikus csoportokba. Egy bevált sorrend:
<div class="
flex items-center justify-between <!-- layout -->
gap-4 <!-- spacing -->
w-full max-w-2xl <!-- méret -->
p-6 <!-- padding -->
bg-white dark:bg-gray-800 <!-- háttér -->
border border-gray-200 <!-- border -->
rounded-xl shadow-md <!-- vizuális stílus -->
hover:shadow-lg <!-- interaktív stílus -->
transition-shadow duration-200 <!-- animáció -->
">2. Prettier Tailwind plugin
A prettier-plugin-tailwindcss automatikusan sorba rendezi a class-eket az ajánlott sorrend szerint:
npm install -D prettier prettier-plugin-tailwindcss.prettierrc:
{
"plugins": ["prettier-plugin-tailwindcss"]
}Ez a plugin az egyik legjobb befektetés a Tailwind projektben – megszünteti a class sorrend körüli vitákat.
3. Clsx helper a kondicionális class-ekhez
Soha ne csinálj template literal class konkatenálást manuálisan:
// ❌ Kerülendő: hibalehetőség és nehezen olvasható
<div className={`flex items-center ${isActive ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-900'} ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}`}>// ✅ Ajánlott: clsx-szel
import { clsx } from 'clsx';
<div className={clsx(
'flex items-center',
isActive ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-900',
isDisabled && 'opacity-50 cursor-not-allowed',
)}>4. A cn() helper (shadcn/ui minta)
A cn() a clsx + tailwind-merge kombinációja – ez az elterjedtebb minta a modern React projektekben:
// lib/utils.ts
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}A tailwind-merge azért kell, mert a sima clsx nem oldja fel a Tailwind konfliktusokat:
// Probléma clsx-szel: mindkét bg class megmarad, undefined viselkedés
clsx('bg-red-500', 'bg-blue-500') // → 'bg-red-500 bg-blue-500'
// Megoldás cn()-nel: a kései osztály nyer
cn('bg-red-500', 'bg-blue-500') // → 'bg-blue-500'Ahol igazán hasznos: prop-ból átadott class-eknél:
function Card({ className, children }) {
return (
<div className={cn('bg-white rounded-xl shadow-md p-6', className)}>
{children}
</div>
);
}
// Használat – a felülíró class működik
<Card className="bg-gray-50 shadow-none">...</Card>5. Mikor bontsd komponensekre?
- Ha ugyanazt a class listát 2-nél többször másolod → komponens
- Ha egy elem class listája 10-nél több class-t tartalmaz és logikát is hordoz → komponens
- Ha a class-ek egy részét prop alapján változtatod → komponens
Összefoglaló
A Prettier plugin és a
cn()helper a két legfontosabb eszköz a professzionális Tailwind fejlesztéshez. Az előbbi automatikusan rendezi a class-eket, az utóbbi biztonságosan kezeli a kondicionális stílusokat és az öröklést.