Rules Hub
Coding Rules Library
Prefer clsx for conditional class names
Use the `clsx` utility to construct className strings conditionally instead of manual string concatenation.
Bad example
| 1 | const Button = ({ isActive, isDisabled }) => { |
| 2 | // Bad: Prone to missing spaces (e.g., "btn-primaryactive") and hard to read |
| 3 | return ( |
| 4 | <button |
| 5 | className={`btn btn-primary${isActive ? ' active' : ''}${isDisabled ? ' disabled' : ''}`} |
| 6 | > |
| 7 | Click me |
| 8 | </button> |
| 9 | ); |
| 10 | }; |
Explanation (EN)
Manually concatenating strings for class names is error-prone. It is easy to miss a leading space (e.g., resulting in 'btn-primaryactive' instead of 'btn-primary active') and the syntax becomes messy with multiple conditions.
Objašnjenje (HR)
Ručno spajanje stringova za nazive klasa podložno je greškama. Lako je zaboraviti razmak (npr. rezultat bude 'btn-primaryactive' umjesto 'btn-primary active'), a sintaksa postaje nepregledna s više uvjeta.
Good example
| 1 | import clsx from 'clsx'; |
| 2 |
|
| 3 | const Button = ({ isActive, isDisabled }) => { |
| 4 | // Good: Handles spaces automatically and logic is declarative |
| 5 | return ( |
| 6 | <button |
| 7 | className={clsx('btn btn-primary', { |
| 8 | 'active': isActive, |
| 9 | 'disabled': isDisabled, |
| 10 | })} |
| 11 | > |
| 12 | Click me |
| 13 | </button> |
| 14 | ); |
| 15 | }; |
Explanation (EN)
Using `clsx` (or `classnames`) handles whitespace management automatically and allows you to define conditional classes in a readable, declarative object format.
Objašnjenje (HR)
Korištenje `clsx` (ili `classnames`) biblioteke automatski upravlja razmacima i omogućuje definiranje uvjetnih klasa u čitljivom, deklarativnom formatu objekta.
Notes (EN)
Always install `clsx` if not present. It is lighter than `classnames` but serves the same purpose.
Bilješke (HR)
Uvijek instaliraj `clsx` ako nije prisutan. Lakši je od `classnames` biblioteke, a služi istoj svrsi.