DEV Community

Cover image for Painless conditional classes with classnames package
m0nm
m0nm

Posted on

Painless conditional classes with classnames package

Hey folks today's post is a small one but i'm going to share with you a pretty neat way to manage your conditional styles.

If you ever worked on conditional classes, chances are you pulled your head trying to put those class names all together with ternary operators and what's not. Today I'll introduce a simple and better way to write conditional classes, Our savior is classnames.

classnames is a simple JavaScript utility for conditionally joining classNames together

First let's see the problem here with a button as an example

const [active, setActive] = useState(false);
<button 
    onClick={() => setActive(true)} 
    className=`btn ${active ? "btn-active" : "btn primary"}`
    >
    Click Me
    </button>
Enter fullscreen mode Exit fullscreen mode

The code above works fine, However we can agree that it looks ugly, If you use CSS modules it may look a bit more readable but it would still look ugly. Especially if you have multiple classes

That's where classnames package comes into play

import classnames from "classnames"

const [active, setActive] = useState(false);

const btnStyles = classnames({
    btn: true, 
    btn-active: active
})

<button 
    onClick={() => setActive(true)} 
    className={btnStyles} >
    Click Me
    </button>
Enter fullscreen mode Exit fullscreen mode

You can see that the syntax is pretty straightforward, classnames will add the 'btn-active' class is active is set to true

Here is the general syntax

const condition = 1 + 1 === 2; 
classnames('foo', {'bar': true, 'baz': condition})
Enter fullscreen mode Exit fullscreen mode

'foo' will always be printed, 'bar' too, but 'baz' will be printed if the expression evaluates to true.

Conclusion

that’s been it! I hope you enjoyed this post, And hopefully you learned something new, If you know any other life-saving tool, share it in the comments!

Thanks for reading, happy conditional styling.

Top comments (0)