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.
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} />
In the example you can see different classes, applied if a given condition evaluates to true. In the example you can apply a class with a boolean value, a boolean variable or a compared string (If match, return true). The class classes.drawer is always applied and does not depend on a condition.
className={clsx(classes.drawer, { // classes.drawer is applied always
[classes.drawerOpen]: true, // classes.drawerOpen is applied always, bool = true
[classes.drawerClose]: !open, // you can also use boolean variable
[classes.drawerRed]: colorVar === 'red', // you can also use string variable
})}
references:
https://stackoverflow.com/questions/57557271/how-to-use-clsx-in-react
No comments:
Post a Comment