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.
classbecomesclassName, becauseclassis a reserved word.forbecomeshtmlFor, for the same reason.- Event handlers are camelCase:
onclickbecomesonClick. - 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.
<div style={{ backgroundColor: "navy", fontSize: 16, paddingTop: "1rem" }}>
Styled
</div>