Course contentsShow
← React
Lesson 97 of 2,3963. JSX FundamentalsFree lesson

The style Prop: Objects Instead of Strings

Why style takes a JavaScript object with camelCase properties rather than a CSS string like in HTML.

The style Prop: Objects Instead of Strings

What you'll learn: Why React's style attribute takes a JavaScript object with camelCase properties instead of a CSS string like regular HTML.

The HTML Way vs The React Way

In HTML, you write inline styles as a string:

<div style="background-color: blue; font-size: 16px;"></div>

In React, the style prop expects a JavaScript object:

<div style={{ backgroundColor: 'blue', fontSize: '16px' }}></div>

Notice the double curly braces: the outer pair means "I'm entering JavaScript land," and the inner pair creates an object.

Why an Object?

React treats everything inside curly braces as JavaScript. Since CSS strings aren't valid JavaScript values you can manipulate easily, React uses objects instead. This lets you:

  • Use JavaScript variables: fontSize: userPreference
  • Calculate values: width: windowWidth / 2
  • Keep type safety and avoid string parsing errors

The camelCase Convention

CSS properties with hyphens (background-color) become camelCase in JavaScript (backgroundColor). This is because hyphens aren't valid in JavaScript object keys without quotes.

// ✅ React way
<div style={{ marginTop: '20px', lineHeight: 1.5 }}></div>

// ❌ Not valid (would need quotes)
<div style={{ 'margin-top': '20px' }}></div>

Numbers without units are treated as pixels for most properties:

<div style={{ padding: 10 }}></div>  {/* becomes 10px */}

Key Takeaway: React's style prop uses JavaScript objects with camelCase properties instead of CSS strings, letting you leverage JavaScript's full power for dynamic styling while maintaining type safety.