How to use clsx in React

clsx is generally used to conditionally apply a given className

This syntax means that some class will only be applied if a given condition evaluates to true

const menuStyle = clsx({
    [classes.root] : true, //always applies
    [classes.menuOpen] : open //only when open === true
})

In this example [classes.menuOpen] (which will evaluate to something like randomclassName123) will only be applied if open === true


clsx basically outputs a string interpolation. So you don’t have to necessarily use it, although is a common practice.

There are many supported syntax that you can check in the official docs

Instead of

<div className={`${classes.foo} ${classes.bar} ${classes.baz}`} />

You can use it like this

const { foo, bar, baz } = classes
const style = clsx(foo, bar, baz)

return <div className={style} />

Leave a Comment

tech