Inline Styles and Style Objects
Inline Styles and Style Objects
1. Inline Styles in React
In traditional HTML, inline styles are declared as semicolon-delimited text strings:
In React JSX, inline styles are passed as JavaScript objects.
This gives styles the full power of JavaScript: dynamic variables, ternary operators, and computed calculations can be seamlessly blended into your component presentation.
2. Converting CSS Properties to camelCase
Because property keys in JavaScript objects cannot contain hyphens without being wrapped in quotes, React converts CSS property names to camelCase:
| Standard CSS | React JSX Style Key |
|---|---|
background-color | backgroundColor |
font-size | fontSize |
margin-top | marginTop |
border-radius | borderRadius |
z-index | zIndex |
box-shadow | boxShadow |
3. Automatic Pixel Units for Numbers
When passing numeric values to dimension properties (such as width, height, margin, padding, fontSize), React automatically appends the 'px' suffix for you:
4. Pros and Cons of Inline Styles
Pros:
- Scoped to the element: Zero risk of style name collisions with other components.
- Dynamic Values: Ideal for styles driven by runtime data (e.g. progress bars, dynamic coordinates, drag-and-drop offsets).
Cons:
- No Pseudo-classes or Pseudo-elements: Inline styles cannot define
:hover,:focus,:active,::before, or::after. - No Media Queries: Responsive breakpoints (
@media (max-width: 768px)) cannot be written in inline style objects. - Performance: Creating new style objects on every render creates minor garbage collection overhead compared to static CSS class names.
Practice Quiz
width: 250?rem units in an inline style object?CSS Stylesheets and Global Class Names
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Cleanup Functions in useEffect | CSS Stylesheets and Global Class Names |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.