Dynamic Styles in React: Styling with State

Give life to your components by changing their appearance in response to user actions and application data.

Lesson ProgressStep 1 of 10
0 EXP

Welcome! Let's learn how to make our components visually react to user actions.

<button>Click Me</button>

The Inline style Prop

The most direct way to style a React component is with the style prop. Unlike in HTML, it doesn't take a string. Instead, it takes a JavaScript object.

All CSS properties must be written in camelCase. For example, background-color becomes backgroundColor, and font-size becomes fontSize.

// This is a JS object
const divStyle = {
  backgroundColor: 'blue',
  color: 'white',
  fontSize: 16
};


// Pass it to the style prop
<div style={divStyle}>Hello World</div>


// Or pass it directly (with double curly braces!)
<div style={{ color: 'red', paddingTop: '10px' }}>
  Error
</div>

System Check

Which of these is the correct syntax for an inline style in React?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🎨
Inline Stylist

Apply an inline style object to a React component.

Stateful Designer

Change a component's style dynamically using the useState hook.

💅
Classy Toggler

Prove your mastery of conditional class name toggling.

Mission: Build a Color Toggler

Complete the component. Add a state variable (e.g., `isActive`). When the `div` is clicked, toggle the state and change the `backgroundColor` between `blue` and `red`.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Assemble the Style Object

Drag the pieces into the correct order to create a valid inline style object.

'blue',
const style = {
fontSize: 16
backgroundColor:
};

Challenge: Complete the Class Toggler

Fill in the missing parts to dynamically toggle a CSS class name.

const [isActive,] = useState(false);
const myClass = `box ${? '' : ''}`;
<div className={myClass}>...</div>

Consult A.D.A.

Community Holo-Net

The Art of Dynamic Styling in React

In React, your component's appearance is often a function of its state. A button is 'disabled', a form input is 'invalid', a todo item is 'completed'. This "state-driven" approach to UI is what makes React so powerful. But what's the best way to translate that state into visual styles?

Let's explore the most common strategies, from the simplest inline styles to more robust, scalable patterns.

Method 1: The Inline style Prop

This is the most direct way to apply styles that come from your component's state. Instead of a CSS string, the style prop in React accepts a JavaScript object.

  • CSS properties are written in camelCase (e.g., backgroundColor instead of background-color).
  • Values are typically strings, but numbers can be used for pixel values (e.g., fontSize: 16).
const [isError, setIsError] = useState(false);


const errorStyle = {
  color: isError ? 'red' : 'black',
  border: isError ? '2px solid red' : '1px solid gray',
  padding: '10px'
};


return <div style={errorStyle}>My Component</div>;

✔️ Pros

  • Simple and direct.
  • Styles are co-located with the component logic.
  • Perfect for styles computed directly from state.

❌ Cons

  • Cannot use pseudo-selectors (:hover, :focus).
  • Cannot use media queries.
  • Can lead to performance issues if a new object is created on every render.

Method 2: Conditional CSS Classes (The "React Way")

This is the most common and recommended approach for dynamic styling. You define your styles in a regular CSS file and use React's state to simply toggle which class names are applied to an element.

/* In your component.js */
const [isActive, setIsActive] = useState(false);


return (
  <button 
    className={`button ${isActive ? 'button-active' : ''}`}
    onClick={() => setIsActive(!isActive)}
  >
    Click Me
  </button>
);


/* In your style.css */
.button {
  background-color: gray;
  transition: background-color 0.3s;
}
.button-active {
  background-color: green;
}
.button:hover {
  opacity: 0.8;
}

This method is so popular that utility libraries like clsx or classnames exist to make combining classes easier:

import clsx from 'clsx';


const classes = clsx('button', {
  'button-active': isActive,
  'button-large': isLarge
});


return <button className={classes}>Click Me</button>;

✔️ Pros

  • Uses the full power of CSS (pseudo-selectors, media queries).
  • Better performance (no new style objects).
  • Keeps styling logic separate from component logic.

❌ Cons

  • Managing class strings can get messy without utilities.
  • Global CSS class name collisions can be an issue.

Advanced Methods: CSS-in-JS & CSS Modules

For larger applications, two other patterns solve the problems of the previous methods:

  • CSS Modules: This is like regular CSS, but each file is automatically scoped to the component that imports it. This solves the "global class name collision" problem.
  • CSS-in-JS (e.g., Styled Components, Emotion): This pattern brings styling *inside* JavaScript. You define components that have styles attached to them. This approach is fantastic for dynamic styling, as you can pass props directly to your styles.
/* Example with Styled Components */
import styled from 'styled-components';


const Button = styled.button`
  background-color: ${(props) => (props.$primary ? 'blue' : 'gray')};
  color: white;
  font-size: 1rem;
  padding: 1rem;


  &:hover {
    opacity: 0.9;
  }
`;


// Usage:
return <Button $primary={isActive}>Click Me</Button>;
Key Takeaway: Start with conditional classes for most of your dynamic styling. Use inline styles only for simple, state-driven values (like a dynamic `width` or `color`). As your application grows, explore CSS Modules or CSS-in-JS for a more scalable system.

React Dynamic Styling Glossary

State (useState)
The "memory" of a component. In styling, it's the data (e.g., isActive: true) that drives the visual change.
style Prop
A React prop that applies inline styles to an element. It accepts a JavaScript object, not a string.
camelCase
The naming convention for CSS properties within a JavaScript style object. Example: background-color becomes backgroundColor.
Ternary Operator
A JavaScript shortcut for an if/else statement, frequently used in React to choose a style or class. Syntax: condition ? 'value-if-true' : 'value-if-false'.
Conditional Class
The practice of dynamically adding or removing CSS class names from an element's className prop based on state. This is the most common and scalable styling pattern.
clsx / classnames
Popular utility libraries that simplify the process of combining multiple and conditional class names into a single string.
CSS-in-JS
A pattern where CSS is written inside JavaScript files, often using tagged template literals. Libraries like Styled Components and Emotion popularized this.
CSS Modules
A system where CSS files are scoped locally to the component that imports them, preventing global class name conflicts.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of senior React developers, who have built and maintained large-scale React applications and understand the nuances of styling for performance and maintainability.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest React (v18+) hooks and patterns, and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!