Chapter 3 of 4

Attributes and Styling

Why it is className not class, and how the style prop differs from a CSS string.

JSX attributes look like HTML attributes but they are really props on a JavaScript object. A few names differ because they clash with reserved words or use JavaScript naming conventions.

  • class becomes className, because class is a reserved word.
  • for becomes htmlFor, for the same reason.
  • Event handlers are camelCase: onclick becomes onClick.
  • Most other attributes keep their HTML name: id, src, alt, href, disabled.
<label htmlFor="email" className="field-label">
  Email
</label>
<input id="email" type="email" onChange={handleChange} disabled={isBusy} />

Values in braces

Quotes give an attribute a literal string. Braces give it the result of an expression, which can be any type.

<img src="/logo.png" />            {/* the string "/logo.png" */}
<img src={logoUrl} />              {/* whatever logoUrl holds */}
<input disabled={isSubmitting} />  {/* a boolean */}
<Chart data={points} />            {/* an array */}

The style prop

Inline styles take an object, not a string, and the property names are camelCased. The double braces you often see are simply an object literal inside a JSX expression.

Outer braces: a JSX expression. Inner braces: the object itself.
<div style={{ backgroundColor: "navy", fontSize: 16, paddingTop: "1rem" }}>
  Styled
</div>