Skip to content
Tutorials Center
My learning

Topics

React Reference ยท JSX Syntax and Rules

JSX expressions

Reference for JSX expressions: embed JavaScript in markup with curly braces, learn where braces are allowed, which values render, and which throw an error.

Curly braces are the door from JSX back into JavaScript. Inside { } you can write any JavaScript expression: a variable, a function call, arithmetic, a template literal, a ternary, an arrow function, a .map() call. The expression is evaluated when the component renders, and its value is placed where the braces are.

Braces work in two places. As a child (<p>{name}</p>) the value becomes content. As an attribute value (<img src={url} />) the value becomes a prop. They do not work for tag names or attribute names, and they cannot hold statements such as if, for or const.

JSX
const total = items.length * price;
return <p title={'Total for ' + items.length}>Sum: {total.toFixed(2)}</p>;

Try it

What each value renders
Expressions, and what is not allowed

Syntax

JSX
<tag attribute={expression}>{expression}</tag>
Position What the value does
Child Strings and numbers become text. Elements are rendered. Arrays are rendered item by item. null, undefined, true and false render nothing.
Attribute attr={expr} The value is passed as the prop. Functions, objects, arrays and numbers keep their type; no string conversion.
Spread {...obj} Only inside a tag, to pass many props. See JSX spread attributes.
Comment {/* ... */} An empty expression with a comment. See JSX comments.

Errors and edge cases: a plain object ({ a: 1 }), a Date, a Map, a Symbol or a function as a child throws or warns. Format the value first: {date.toISOString()}, {JSON.stringify(obj)}. A bigint renders as its digits.

Usage notes

  • Expressions only. Anything you can put on the right side of = works. For logic that needs statements, compute a variable before the return, or use an immediately invoked function as a last resort.
  • Double braces are not special syntax. style={{ color: 'red' }} is an attribute expression { ... } that contains an object literal { color: 'red' }.
  • 0 and NaN render. Unlike false, they are valid text (React also logs a development warning for NaN). This is the cause of the classic {count && <List />} bug, which prints 0 when the count is zero. See Conditional rendering.
  • Text is escaped. A string that contains <script> is shown as text, not run. This is how React prevents most XSS. The exception is dangerouslySetInnerHTML.
  • Evaluated every render. Expressions run each time the component renders. Move expensive work out of the markup or into useMemo().
  • Side effects do not belong here. Do not call setState, fetch or write to variables inside braces; render must stay pure.
  • Quotes versus braces. title="x" is a literal string; title={x} is the variable x. Mixing them (title="{x}") gives the literal text .
  • Keys with .map(). A mapped array needs a key on each item. See JSX lists.