← Back to Chapters

Inline CSS in React

? Inline CSS in React

⚛️ React   ? Inline CSS   ⚡ Dynamic Styling

⚡ Quick Overview

Inline CSS in React lets you style elements directly using the style attribute. Instead of writing styles in separate CSS files, you define them as JavaScript objects and pass them into JSX.

This is especially useful for dynamic styling, where style values depend on component state or props, such as active buttons, theme toggles, or validation states.

  • Styles are written as JavaScript objects.
  • CSS properties use camelCase, not kebab-case.
  • Perfect for small, self-contained, and dynamic UI elements.

? Key Concepts

  • Style attribute as an object: style in JSX expects an object, not a string.
  • camelCase properties: e.g., backgroundColor instead of background-color.
  • Reusable style objects: Define once, reuse across components.
  • Dynamic styles: Use state/props to change styles at runtime.
  • Merging styles: Combine multiple objects using the spread operator (...).

? Syntax & Theory

In React, inline styles are passed as a JavaScript object to the style prop:

  • Property names use camelCase.
  • Values are usually strings (e.g., "10px", "red").
  • You can store style objects in variables for reuse.
? View JSX Inline Style Syntax
// Generic pattern for using inline styles in JSX
const styles = {
  backgroundColor: "lightblue",
  padding: "12px",
  borderRadius: "6px"
};

function MyComponent() {
  return (
    <div style={styles}>Hello with inline styles</div>
  );
}

? Basic Inline Styling

Inline styles in React are defined as objects, where property names are written in camelCase instead of kebab-case. You pass this object directly to the style attribute.

? View Basic Inline Styling Example
// Simple component using inline styles on a div
function InlineExample() {
  return (
    <div
      style={{
        backgroundColor: "lightblue",
        color: "darkblue",
        padding: "15px",
        borderRadius: "8px",
        textAlign: "center"
      }}
    >
      <h4>Inline CSS Example</h4>
      <p>This element is styled directly using the style attribute.</p>
    </div>
  );
}

Notice that properties like background-color become backgroundColor in JSX.

? Using Style Objects

It is often cleaner to define styles in a variable or constant, especially when you reuse the same styles in multiple places.

? View Style Object Example
// Reuse a style object across the component
function ObjectStyleExample() {
  const boxStyle = {
    border: "2px solid #007bff",
    borderRadius: "5px",
    padding: "10px",
    color: "#333",
    backgroundColor: "#eaf3ff",
    textAlign: "center"
  };

  return (
    <div style={boxStyle}>
      <h5>Using a Style Object</h5>
      <p>Style objects make code cleaner and reusable.</p>
    </div>
  );
}

The style attribute accepts a JavaScript object, not a string — this allows programmatic control and reuse of styles.

? Dynamic Inline Styles (with State)

You can dynamically change styles based on component state or user actions, such as toggling between two button colors.

? View Dynamic Style Example
// Change button color based on isActive state
function DynamicStyleExample() {
  const [isActive, setIsActive] = React.useState(false);

  const buttonStyle = {
    padding: "10px 20px",
    backgroundColor: isActive ? "#28a745" : "#6c757d",
    color: "#fff",
    border: "none",
    borderRadius: "4px",
    cursor: "pointer"
  };

  return (
    <div className="text-center">
      <button
        style={buttonStyle}
        onClick={() => setIsActive(!isActive)}
      >
        {isActive ? "Active" : "Inactive"}
      </button>
    </div>
  );
}

Inline styling works perfectly with React’s state-driven rendering to create interactive UI effects like toggles, highlights, and conditional emphasis.

⚙️ Merging Multiple Styles

You can merge multiple style objects using the ... spread operator. This lets you keep base styles separate from variant styles (success, warning, error, etc.).

? View Merging Style Objects Example
// Combine base styles with variant styles using the spread operator
function MergeStyleExample() {
  const baseStyle = { padding: "10px", color: "#fff" };
  const successStyle = { backgroundColor: "green" };
  const warningStyle = { backgroundColor: "orange" };

  const [mode, setMode] = React.useState("success");

  const style =
    mode === "success"
      ? { ...baseStyle, ...successStyle }
      : { ...baseStyle, ...warningStyle };

  return (
    <div className="text-center">
      <h5 style={style}>
        {mode === "success" ? "Success Mode" : "Warning Mode"}
      </h5>
      <button
        className="btn btn-outline-dark mt-2"
        onClick={() => setMode(mode === "success" ? "warning" : "success")}
      >
        Toggle Mode
      </button>
    </div>
  );
}

This approach keeps styles modular and allows easy combination of reusable objects while still remaining expressive and readable.

? Live Output & Explanation (Conceptually)

  • InlineExample: Renders a blue box with rounded corners and centered text styled directly via style.
  • ObjectStyleExample: Uses a reusable boxStyle object to keep JSX cleaner and styles consistent.
  • DynamicStyleExample: Button toggles between “Active” (green) and “Inactive” (gray) while the background color changes with state.
  • MergeStyleExample: Heading background switches between green “Success Mode” and orange “Warning Mode” using merged style objects.

In a real React app, placing these components inside a root component (and rendering with ReactDOM.render or createRoot) would show each of these behaviors visually.

? Pros & Cons of Inline CSS

  • ✅ Pros:
    • Dynamic and easy to modify with state/props.
    • Encapsulated within the component — no external CSS dependencies.
    • Good for small or reusable elements (like buttons, badges, or status labels).
  • ⚠️ Cons:
    • No pseudo-classes like :hover or :focus directly.
    • No media queries for responsive design.
    • Harder to maintain in large projects compared to CSS files, modules, or utility frameworks.

? Tips & Best Practices

  • Use inline styles mainly for quick prototypes or component-specific conditions.
  • Keep style objects outside the render logic when possible for better performance.
  • Combine inline CSS with class-based styling (e.g., Bootstrap, Tailwind) for layout and global styles.
  • Prefer CSS-in-JS libraries (like styled-components or Emotion) if you need dynamic + scoped styles at scale.
  • Use descriptive style object names like buttonPrimary or alertWarning to make code self-documenting.

? Try It Yourself

  1. Create a box that changes its background color every time you click a button using inline styles and state.
  2. Build a toggle button that switches between “Dark” and “Light” mode using inline styles on a wrapper <div>.
  3. Experiment with merging multiple style objects (base + success + warning + error) for better modularity.
  4. Add inline conditional styles to highlight invalid input fields (e.g., red border when the field is empty).
  5. Create a “badge” component that accepts type as a prop and uses inline styles to change its color.

Goal: Learn to use inline CSS effectively for component-level and dynamic styling in React using JavaScript objects, state, and props.