Capítulo 14 de 116

Chapter 14: JavaScript in JSX with Curly Braces

Core Idea

Curly braces {} are the only escape hatch from JSX back into plain JavaScript — they work in exactly two positions (as tag text content, or immediately after = in an attribute), and everything else follows from that.

Key Concepts

  • String attributes use quotes directly: alt="Gregorio Y. Zara". To use a JS value instead, swap quotes for curly braces: alt={description}.
  • Any JS expression is valid inside {} — a variable, a function call ({formatDate(today)}), a computed string, etc. Statements (like if) are not expressions and don't work directly inside {}.
  • The two valid positions: as JSX text (<h1>{name}'s Todos</h1>) or as an attribute value right after = (src={avatar}). <{tag}> and src="{avatar}" (quotes around the braces) are both invalid/wrong.
  • "Double curlies" are not special syntaxstyle={{ backgroundColor: 'black' }} is a plain JS object literal { backgroundColor: 'black' } passed through the ordinary {} JSX escape hatch. Inline style properties are camelCase (backgroundColor, not background-color).
  • Rendering an object directly throws: <h1>{person}</h1> where person is an object fails with "Objects are not valid as a React child" — React needs a string/number/element, so you must reach into the object ({person.name}) first.

Code Examples

const person = {
  name: 'Gregorio Y. Zara',
  theme: { backgroundColor: 'black', color: 'pink' }
};

<div style={person.theme}>
  <h1>{person.name}'s Todos</h1>
</div>
  • What it demonstrates: pulling both a style object and a string out of one JS object via the same {} escape hatch — style={person.theme} (object) and {person.name} (string).

Key Takeaways

  1. {} always means "evaluate this as JavaScript" — never wrap it in quotes, or it becomes a literal string instead.
  2. style={{...}} isn't magic — it's just an object literal nested inside the normal curly-brace escape hatch, so any JS object you already have (e.g. person.theme) works the same way.
  3. React refuses to render a bare object as a child — always drill down to the actual string/number field you want.

Connects To

  • Ch 13 (Writing Markup with JSX): the three structural rules this chapter's {} syntax operates within.
  • Ch 15 (Passing Props to a Component): {} is exactly how prop values get passed down from JSX.