Dynamic Styles in React: Changing Appearance with State

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

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

<button>Click Me</button>

The Trigger: State

The foundation of dynamic styles is state. By using the useState hook, you create a variable that, when changed, tells React to re-render the component. This re-render is your opportunity to apply new styles.

The Mechanism: The `style` Prop

In JSX, you apply inline styles with the style prop. Unlike HTML, it doesn't take a string. Instead, it takes a JavaScript object. CSS properties are written in camelCase, for example, backgroundColor instead of `background-color`.

Combining State and Style

The magic happens when you combine state and the style prop. You create a style object where the values are determined by your state variables, often using a ternary operator. For example: { backgroundColor: isActive ? 'green' : 'gray' }.

The Result: A Responsive UI

When an event (like a button click) updates the state, React re-evaluates the style object and applies the new CSS values to the DOM. This creates a seamless and instant visual feedback loop for the user, making your application feel alive and responsive.

Practice Zone


Interactive Test 1: Match the Syntax

Complete the code to apply a dynamic background color to the button.

Arrastra en el orden correspondiente.


Arrastra las opciones:

style
backgroundColor

Completa el código:

<button ______={{ backgroundColor: 'blue' }}>
const buttonStyle = { ______: 'blue' }
Unlock with Premium

Interactive Test 2: Complete the Logic

Fill in the blanks to create a button that toggles its color and an input field that changes its border color based on the same state.

Rellena los huecos en cada casilla.

function DynamicComponent() {
  const [isActive, setIsActive] = useState(false);

  const styles = {
    backgroundColor:  ? 'green' : 'gray',
    borderColor: isActive ? 'green' : 'red',
  };

  return (
    <div>
      <button ={ {backgroundColor: styles.backgroundColor} } onClick={() => setIsActive(!isActive)}>
        Toggle
      </button>
      <input style={ {borderColor: styles.borderColor} } />
    </div>
  );
}
Unlock with Premium

Practice Example: Code Editor

Create a component with a single `div`. When the mouse hovers over it, its background should turn lightblue. When the mouse leaves, it should revert to white. (Hint: you'll need two state variables or one state variable that holds an object).

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

function HoverComponent() { const [isHovering, setIsHovering] = useState(false); const divStyle = { width: '100px', height: '100px', border: '1px solid black', backgroundColor: isHovering ? 'lightblue' : 'white', }; return ( <div style={divStyle} onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)} > Hover over me </div> ); }

Unlock with Premium

Knowledge Check

In JSX, what data type does the `style` prop expect?


Unlock with Premium

Styling Logic in Action

Dynamic styling is a powerful tool. While inline styles are great for state-driven changes, React's flexibility allows for even more robust styling strategies.


1. Conditional CSS Classes

For more complex styling, it's often better to toggle CSS classes instead of managing many inline style properties. You can store your styles in a separate CSS file and conditionally apply class names. This keeps your JSX cleaner and leverages the full power of CSS.

// In your component
<div className={`card ${isSelected ? 'active' : ''}`}>

// In your CSS
.card.active {
  border-color: blue;
  box-shadow: 0 0 10px blue;
}
Active Card

2. Form Validation Feedback

Dynamic styles are essential for good user experience in forms. You can change an input's border color based on a validation state, instantly telling the user if their input is valid or not.

const [error, setError] = useState('Invalid email');

const inputStyle = {
  borderColor: error ? 'red' : 'green',
};

3. Creating Themes (e.g., Dark Mode)

The same principles apply to app-wide theming. A top-level state or Context can hold the current theme (e.g., 'light' or 'dark'). Components can then use this theme to select their styles, allowing for a complete UI transformation with a single state change.

const theme = {
  background: isDarkMode ? '#111' : '#EEE',
  color: isDarkMode ? '#EEE' : '#111',
};

return <div style={theme}>...</div>;
Dark Mode Enabled

Practical Takeaway: By tying styles directly to state, you create UIs that provide clear, immediate visual feedback, making your applications more intuitive and engaging for the user.

Dynamic Styles Glossary

Inline Styles
CSS styles applied directly to a JSX element using the `style` prop. This is the primary method for applying state-driven styles.
Style Object
The JavaScript object passed to the `style` prop. Its keys are camelCased CSS properties (e.g., `fontSize`) and its values are strings or numbers.
camelCase
The naming convention required for CSS properties within a JavaScript style object. For example, the CSS property `background-color` becomes `backgroundColor` in JavaScript.
State (via `useState`)
The data that drives the dynamic changes. When state is updated with its setter function (e.g., `setIsActive(true)`), React re-renders the component, applying any new styles.
Event Handler
A function that responds to user interaction, such as `onClick` or `onMouseEnter`. Event handlers are typically used to call state setter functions, thus triggering the style change.