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.
<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:
Completa el código:
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> ); }
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).
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;
}
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>;
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.