⚡️3 Ways Conditionally Render CSS in React

Create new react app

npx create-react-app my-app
cd my-app
npm start

Method 1:

Syntax

{[ your_class_name]: conditon}

Example

In this method, we are going to use CSS modules. In order to merge two classes we use clsx library.

Install clsx

npm install clsx

Now once you installed let dive into App.js

import styles from "./styles.module.css";
import clsx from "clsx";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={clsx(styles.baseText, { [styles.heading]: title })}>
        Sample Heading
      </h1>
      <h1 class={styles.description}>Here goes description</h1>
    </div>
  );
}

styles.module.css

.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

Link

Method 2:

Syntax

conditon && yourstyle

App.js

import styles from "./styles.module.css";
import clsx from "clsx";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={clsx(styles.baseText, title && styles.heading)}>
        Sample Heading
      </h1>
      <h1 class={styles.description}>Here goes description</h1>
    </div>
  );
}

styles.module.css

.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

Method 3:

Syntax

{`${condition}` ? "classname_1" : "classname_2"}

Example

App.js

import "./styles.css";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={`${title}` ? "heading" : "baseText"}>Sample Heading</h1>
      <h1 class="description">Here goes description</h1>
    </div>
  );
}

styles.css

.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

Result

22