functionNavLink({ href, isActive, children }){// Template literal approachconst className =`nav-link ${isActive ?'nav-link--active':''}`;return<a href={href} className={className}>{children}</a>;}// Helper function for multiple conditional classesfunctionclassNames(...classes){return classes.filter(Boolean).join(' ');}functionCard({ featured, compact, className }){return(<div
className={classNames('card',
featured &&'card--featured',
compact &&'card--compact',
className
)}>{/* ... */}</div>);}
Note Use a small classNames helper or the popular 'clsx' package to compose conditional classes cleanly. Avoid complex ternary chains inside className attributes -- extract the logic to keep JSX readable.
// With clsx or classnames libraryimport clsx from'clsx';<div className={clsx('base',{ active: isActive, disabled: isDisabled })}/>
Example
// Using the clsx libraryimport clsx from'clsx';functionStatusChip({ status }){return(<span
className={clsx('chip',{'chip--success': status ==='active','chip--warning': status ==='pending','chip--danger': status ==='error','chip--muted': status ==='inactive',})}>{status}</span>);}// Without a libraryfunctionStatusChipManual({ status }){const chipClass =['chip',
status ==='active'&&'chip--success',
status ==='error'&&'chip--danger',].filter(Boolean).join(' ');return<span className={chipClass}>{status}</span>;}
Note The clsx library (or classnames) accepts strings, objects, and arrays. Object keys are included when their value is truthy. It is lightweight (~228 bytes) and widely used in the React ecosystem.
Frequently asked questions
How does React handle className?
React covers this with 2 copy-ready snippets on this page. The "className Patterns" snippet in React uses `<div className="static-class" />`.
Which code does the React example use?
The "className Patterns" snippet uses `<div className="static-class" />`, from the Styling section of the React cheat sheet.
What other React snippets are shown for "className"?
Besides "className Patterns", this page also shows "Conditional Classes".
Is there anything to watch out for?
Yes. For "className Patterns": Use a small classNames helper or the popular 'clsx' package to compose conditional classes cleanly. Avoid complex ternary chains inside className attributes -- extract the logic to keep JSX readable.