How to use clsx in React

后端 未结 3 1945
迷失自我
迷失自我 2021-01-31 08:50

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

The construct

className={clsx(classes.menuButton, open &         


        
3条回答
  •  悲&欢浪女
    2021-01-31 09:17

    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

    You can use it like this

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

提交回复
热议问题