How to Conditionally Apply Class Attributes with React?

Sonmetimes, we want to conditionally apply class attributes with React.

In this article, we’ll look at how to conditionally apply class attributes with React.

Conditionally Apply Class Attributes with React

To conditionally apply class attributes with React, we can use the classnames library.

We install it by running:

npm i classnames

Then we write:

import classNames from "classnames";
import React from "react";

const btnGroupClasses = classNames("btn-group", "pull-right", {
  show: true,
  hidden: false
});

export default function App() {
  return (
    <div className={btnGroupClasses}>
      <button>button</button>
    </div>
  );
}

We call classNames with the class name strings we want to add.

And we pass in an object with show set to true and hidden set to false to add the showclass and omit thehidden` class.

We assign the returned class name string to btnGroupClasses.

And then we set className to btnGroupClasses to add the classes.

Therefore, the div should have btn-group, pull-right, and show classes added.

Conclusion

To conditionally apply class attributes with React, we can use the classnames library.