React › Styling in React (CSS Modules, Styled Components & Tailwind)
How would you conditionally apply different CSS classes based on a component's state, such as showing an active style?
AdvancedAnswer
You build the class name string dynamically based on your current state or props, often using a small helper library like clsx or classnames to make combining multiple conditional classes cleaner and easier to read than manually joining strings together.
import clsx from 'clsx';
function Tab({ isActive, label, onClick }) {
return (
<button
className={clsx('tab', { 'tab-active': isActive })}
onClick={onClick}
>
{label}
</button>
);
}Real-world example A tabs component highlights whichever tab is currently selected by conditionally adding an extra tab active class, using the clsx library to keep the conditional class logic clean and easy to read.