DEV Community

Cover image for 3 Ways Conditionally Render CSS in ReactJS
Jasur Kurbanov
Jasur Kurbanov

Posted on • Edited on

3 Ways Conditionally Render CSS in ReactJS

Create new react app

npx create-react-app my-app
cd my-app
npm start
Enter fullscreen mode Exit fullscreen mode

Method 1:

Syntax

{[ your_class_name]: conditon}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

styles.module.css

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

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

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

Enter fullscreen mode Exit fullscreen mode

Link

Method 2:

Syntax

conditon && yourstyle
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

styles.module.css

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

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

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

Enter fullscreen mode Exit fullscreen mode

Method 3:

Syntax

{`${condition}` ? "classname_1" : "classname_2"}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

styles.css

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

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

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

Enter fullscreen mode Exit fullscreen mode

Result

Image description

Source code for this tutorial

Top comments (0)