Skip to content

Instantly share code, notes, and snippets.

@calebergh
Last active June 30, 2021 16:17
Show Gist options
  • Save calebergh/9a5c10d500285a146667af85439977e0 to your computer and use it in GitHub Desktop.
Save calebergh/9a5c10d500285a146667af85439977e0 to your computer and use it in GitHub Desktop.
React vs Angular - CSS Class Names

Something as trivial as adding a css classname has many pitfalls:

React / JSX way:

wrong, done all the time, ends up adding "undefined" as classname unintentionally
<li className={classNameVariable)}>{item.name}</li>

resolves "undefined" problem, but more verbose, feels a bit gross
<li className={classNameVariable || "")}>{item.name}</li>

but wait, what if it's just a boolean?
<li className={classBoolean ? 'conditional-class' : ''}>{item.name}</li>

now let's mix in a static class (space separators get wierd, result in trailing spaces always rendered, which feels slopy)
<li className={'static-class ' + (classNameVariable || ""))}>{item.name}</li>

with a boolean instead of className string
<li className={'static-class ' + (classBoolean ? 'conditional-class' : ''))}>{item.name}</li>

and things really get weird if you need multiple classes with variables and / or static classes....
wrong, "undefined" problem, class always has trailing space
<li className={classNameVariable + ' static-class ' + (classBoolean ? 'conditional-class' : '')}>{item.name}</li>

best result, but verbose, not-obvious to author, and harder to maintain
note that the class "computation" can be pulled out into a javascript line above the template for cleaner results,
but still verbose and complicated
<li className={['static-class', classNameVariable, (classBoolean ? 'conditional-class' : '')].filter(c => !!c).join(' ')}>{item.name}</li>

Angular Way:

(using pug templating language, which BTW is not available in React / JSX)

just doesn't have "undefined" problem
li([ngClass]="classNameVariable") {{item.name}}

if it's just a boolean
li([class.conditional-class]="classBoolean") {{item.name}}

mix in that static class...
li.static-class([ngClass]="classNameVariable") {{item.name}}

and with the boolean variable...
li.static-class([class.conditional-class]="classBoolean") {{item.name}}

multiple classes
li.static-class([ngClass]="classNameVariable", [class.conditional-class]="classBoolean") {{item.name}}

and just for fun, robust support for even more options
li.static-class.another-static-class([ngClass]="classNameVariable", [class.conditional-class]="classBoolean", [class.another-class]="otherClassBoolean") {{item.name}}

Side by side for comparison:

Real-world, in-production-code use case
<li className={['static-class', classNameVariable, (classBoolean ? 'conditional-class' : '')].filter(c => !!c).join(' ')}>{item.name}</li>

li.static-class([ngClass]="classNameVariable", [class.conditional-class]="classBoolean") {{item.name}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment