← Back to Chapters

Dynamic Styles with State

⚛️ Dynamic Styles with State

⚡ Quick Overview

In React, dynamic styles let you change how components look based on state or props. This powers interactive UIs like active buttons, form validation states, or light/dark themes.

You can implement dynamic styling using inline style objects, conditional class names, and even CSS variables that update when state changes.

? Key Concepts

  • State-driven UI: Visual appearance follows component state or props.
  • Inline styles: Pass a JavaScript object to the style prop.
  • Conditional classes: Toggle class names using expressions inside className.
  • CSS variables: Update --custom-variables from React for global theming.
  • Animations & transitions: Use CSS transitions with state changes for smooth effects.

? Syntax & Approaches

The most common patterns for dynamic styling in React are:

  • Inline styles: <div style={boxStyle}>...</div> where boxStyle is a JS object computed from state.
  • Conditional classes: className={`btn ${active ? "active" : "inactive"}`} to switch between CSS rules.
  • CSS variables: Use document.documentElement. style.setProperty() to change theme colors.
  • Animated transitions: Combine transition in CSS with state toggles in React.

? Example 1: Inline Dynamic Styles

Here, we bind a boxStyle object to the style prop and compute its values from the component state. The background color switches when the count reaches 5 or more.

? View Code Example
// React component with inline dynamic styles based on count
import React, { useState } from "react";

function InlineDynamicExample() {
const [count, setCount] = useState(0);

const boxStyle = {
padding: "20px",
backgroundColor: count >= 5 ? "#28a745" : "#ffc107",
color: "#fff",
borderRadius: "8px",
textAlign: "center",
transition: "background-color 0.3s ease"
};

return (
<div style={boxStyle}>
<h4>Count: {count}</h4>
<button
className="btn btn-dark me-2"
onClick={() => setCount(count + 1)}
>
+</button>
<button
className="btn btn-secondary"
onClick={() => setCount(0)}
>
Reset</button>
</div>
);
}

export default InlineDynamicExample;

? What Happens Here?

  • count starts at 0.
  • Each click on + increases the count by 1.
  • When count >= 5, the box background turns green, otherwise it stays yellow.
  • Clicking Reset sets the count back to 0 and restores the yellow background.

? Example 2: Dynamic Class Names

Conditional class names are cleaner when you have more complex CSS. Here, we toggle between .active and .inactive styles.

? View Code Example (DynamicButton.css)
/* Button styles with active/inactive states */
.btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
color: white;
transition: background 0.3s ease;
}

.btn.active {
background-color: #28a745;
}

.btn.inactive {
background-color: #6c757d;
}
? View Code Example (DynamicButton.js)
// React button that toggles active/inactive classes
import React, { useState } from "react";
import "./DynamicButton.css";

function DynamicButton() {
const [active, setActive] = useState(false);

return (
<div className="text-center">
<button
className={`btn ${active ? "active" : "inactive"}`}
onClick={() => setActive(!active)}
>
{active ? "Active" : "Inactive"}
</button>
</div>
);
}

export default DynamicButton;

? What Happens Here?

  • The button starts in the inactive gray state.
  • On each click, active toggles between true and false.
  • The class name switches between btn active and btn inactive.
  • The CSS decides the final colors and hover behavior.

? Example 3: Dynamic Styles with CSS Variables

Using CSS variables, you can create powerful theme switches. React updates --theme-bg and --theme-color so the whole UI can respond.

? View Code Example
// Theme toggle using CSS variables
import React, { useState, useEffect } from "react";

function ThemeToggle() {
const [dark, setDark] = useState(false);

useEffect(() => {
document.documentElement.style.setProperty(
"--theme-bg",
dark ? "#212529" : "#f8f9fa"
);
document.documentElement.style.setProperty(
"--theme-color",
dark ? "#f8f9fa" : "#212529"
);
}, [dark]);

const pageStyle = {
backgroundColor: "var(--theme-bg)",
color: "var(--theme-color)",
height: "150px",
display: "flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.3s ease"
};

return (
<div style={pageStyle}>
<button
className="btn btn-outline-info"
onClick={() => setDark(!dark)}
>
{dark ? "Light Mode" : "Dark Mode"}
</button>
</div>
);
}

export default ThemeToggle;

? What Happens Here?

  • dark controls whether the theme is dark or light.
  • useEffect updates the CSS variables on every change of dark.
  • The outer div reads the variables using var(--theme-bg) and var(--theme-color).
  • The button label flips between Light Mode and Dark Mode.

⚙️ Example 4: React Animations with Dynamic State

Combine state with CSS transitions or keyframes to animate style changes smoothly. Here, a box grows and changes color when toggled.

? View Code Example (AnimatedBox.js)
// Animated box that expands using a CSS transition
import React, { useState } from "react";
import "./AnimatedBox.css";

function AnimatedBox() {
const [expanded, setExpanded] = useState(false);

return (
<div className="text-center">
<div className={`box ${expanded ? "expanded" : ""}`}></div>
<button
className="btn btn-primary mt-3"
onClick={() => setExpanded(!expanded)}
>
Toggle Box</button>
</div>
);
}

export default AnimatedBox;
? View Code Example (AnimatedBox.css)
/* Box transitions in size and color when expanded */
.box {
width: 100px;
height: 100px;
background-color: #0d6efd;
margin: auto;
border-radius: 8px;
transition: all 0.4s ease;
}

.box.expanded {
width: 200px;
height: 200px;
background-color: #198754;
}

? What Happens Here?

  • The box starts as a small blue square.
  • Clicking Toggle Box flips the expanded state.
  • The class name switches between box and box expanded.
  • CSS transitions animate the width, height, and background color for a smooth effect.

? Common Use Cases

  • ✅ Toggle between light and dark themes.
  • ✅ Highlight selected items or active tabs.
  • ✅ Apply success/error styles in form validation.
  • ✅ Change styles based on API responses or props.
  • ✅ Animate state transitions smoothly.

? Tips & Best Practices

  • Drive all visual changes from state or props for predictability.
  • Prefer class toggling for complex styling instead of huge inline style objects.
  • Use CSS transitions to avoid jarring, instant jumps in the UI.
  • Keep inline styles minimal and reserved for highly dynamic values (like colors or sizes).
  • Reuse CSS variables for theming instead of duplicating color values everywhere.

? Try It Yourself / Practice Tasks

  1. Build a Like button that fills with color and changes text when clicked.
  2. Create a Night Mode toggle using CSS variables and React state.
  3. Animate a progress bar that grows based on a numeric state value.
  4. Make a tab component where the active tab has a highlighted background.
  5. Experiment with combining className toggles and CSS transitions for smooth visual effects.

Goal: Master dynamically styling React components using state and props to create interactive, responsive, and visually engaging user interfaces.