Conditional Class Rendering in React using CLSX

Janith Silva
2 min readAug 14, 2022

--

What is CLSX and when do we need to use it?

I mentioned about clsx in my previous blog post and I needed to write a new one explaining it more. Say goodbye to not-so-readable multiple-class renderings like this!

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

Ans say hello to clx. — Even though it was here for quite some time, I just discovered it :)

What is CLSX?

A tiny (228B) utility for constructing className strings conditionally.
Also serves as a faster & smaller drop-in replacement for the classnames module.

This is the definition we find in the npm package documentation. Basically, it lets you conditionally set react class names (and also enables you to pass multiple class names — obviously).

How to install

You can easily install this to your project using npm like this.

$ npm install --save clsx

Usage

Let me walk you through a simple example where we can use clsx.

So as you can see in this example, there is this presidency variable where we set the class name list according to some booleans. Let me explain line by line why and what it does,

  • We use clxs to pass class names into the package. clsx() function from the package of the same name is a JavaScript utility used to set up conditions for setting the value of the className attribute. It accepts an unlimited number of arguments not limited to one specific type.
  • We should pass the class list as an array. So ranil, mahinda, namal, gotabaya all are style classes. We need a way to pass one or more of those depending on some external booleans right? we set the ranil class to true ; basically, it says that the ranilclass will be executed always no matter what.
  • Unlike ranil class, mahinda class will only be set when the isRanilNotPresident is true.
  • Same as mahinda , both gotabaya and namal classes have their own conditions. So depending on their value, the classes will be set.
  • gotabaya is set when the isRanilNotPresident is true and also beforeAragalaya is true.

This is not the only way to set the conditions, There are many supported syntaxes that you can check in the official docs.

I think this will help you to code a little better and be a bit more reader-friendly. Thanks for reading and will catch you in the next one. Peace!

--

--

Responses (1)