Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Better conditional css classes in React
Victor Ocnarescu
Victor Ocnarescu

Posted on

     

Better conditional css classes in React

Something short and sweet: let's explore one of the better ways to write conditional classes in React. I will use a simple menu item functional component and some pseudocode.

constMenuItem=({children})=>{// TODO: add classes when a menu item is "active"// TODO: optionally add classes for dark themereturn(<liclassName="menu-item">{children}</li>);};
Enter fullscreen modeExit fullscreen mode

First attempt: Logical && operator

constMenuItem=({children})=>{return(<liclassName={`menu-item${isActive&&'menu-item-active'}`}>{children}</li>);};
Enter fullscreen modeExit fullscreen mode

Cons: This code actually has a hidden bug. For falsy values thefalse css class appears in the DOM. Let's get rid of the bug in our next attempt.

Second attempt: Ternary operator

constMenuItem=({children})=>{return(<liclassName={`menu-item${isActive?'menu-item-active':''}`}>{children}</li>);};
Enter fullscreen modeExit fullscreen mode

Cons: This code does not have any hidden bugs like before, but looks too complex for such a simple task. It is also not so readable as it should be and can get event worse: imagine having other use conditions likeisDarkTheme.

Third attempt: Constructing className strings

The third attempt and my personal favorite is using a function (npm package) to construct the className. It is actually a mix of the first 2 attempts:

constMenuItem=({href,children})=>{return(<liclassName={classnames('menu-item',isActive&&'menu-item-active',isDarkTheme&&'menu-item-dark')}>{children}</li>);};
Enter fullscreen modeExit fullscreen mode

NPM packages

Here is a list of NPM packages and their bundle sizes. They all have the same implementations, so you can choose which one suits you best:

Conclusion

We as developers always read more code than we write. That's why I always choose to write code that is more readable and easily understandable by anyone.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

11+ years of experience tangled in the world wide web.
  • Location
    Europe
  • Joined

More fromVictor Ocnarescu

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp