React Dynamic Styling

Pascual Vila
Frontend Instructor // Code Syllabus
A static UI is boring. Modern web applications require dynamic interfaces that respond to user interaction and data state. In React, we handle this by deeply integrating CSS with JavaScript logic.
Inline Styles as Objects
In traditional HTML, the `style` attribute expects a string (e.g., `style="color: red;"`). In React, passing a string will throw an error. React expects a JavaScript object mapping CSS property names to their corresponding values.
This is why property names must be written in `camelCase`. For instance, `background-color` becomes backgroundColor. This object-based approach prevents security vulnerabilities like XSS and allows easy manipulation using JS variables.
Conditional Classes
While inline styles are useful, heavily styling components this way can lead to bloated code and lack of reusability (like missing hover states). Instead, managing classes conditionally is often the preferred approach.
Using ES6 Template Literals and the Ternary operator makes toggling classes clean and powerful. className={`btn ${isActive ? 'active' : ''}`} allows you to chain multiple static classes with dynamic ones based on the component's state or props.
Advanced Strategies (CSS-in-JS)+
Once you outgrow basic inline styles and conditional classes, ecosystems like `styled-components` or `CSS Modules` allow scoping styles strictly to components while retaining the power of dynamic JavaScript interpolation.