22
⚡️3 Ways Conditionally Render CSS in React
Create new react app
npx create-react-app my-app
cd my-app
npm start
{[ your_class_name]: conditon}
In this method, we are going to use CSS modules. In order to merge two classes we use clsx
library.
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;
}
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;
}
{`${condition}` ? "classname_1" : "classname_2"}
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;
}
22