Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

reactjs - How to use clsx in React

I am trying to understand some uses of clsx in assigning classnames to a component in React.

The construct

className={clsx(classes.menuButton, open && classes.hide)} 

is clear enough. It applies 'classes.menuButton', and also applies 'classes.hide' if the value of the boolean 'open' is true.

My question relates to this second example:

className={clsx(classes.appBar, {[classes.appBarShift]: open })}

This will apply 'classes.appBar'. But what is the meaning of the second parameter?

question from:https://stackoverflow.com/questions/57557271/how-to-use-clsx-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 performs a string interpolation. So you don't have to necessarily use it to conditionally apply classes.

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} />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...