Components and JSX

Put JavaScript expressions in braces

Insert values and calculate attributes with expressions while keeping statements outside the returned JSX.

Curly braces switch from JSX markup to a JavaScript expression.

const name = 'Ada'

return <h1>Hello, {name.toUpperCase()}</h1>

The page shows Hello, ADA.

You can use variables, property access, function calls, array methods, and conditional expressions inside braces.

Statements do not fit inside braces. An if statement changes control flow but does not produce a value. Put it before the return:

function Price({ amount }) {
  if (amount === 0) {
    return <strong>Free</strong>
  }

  return <span>€{amount}</span>
}

Pass amount={0} and you get bold Free. Pass amount={12} and you get €12.

Use a ternary when both choices fit naturally inside the surrounding markup:

<p>{online ? 'Online' : 'Offline'}</p>

Booleans, null, and undefined render nothing. This makes showDetails && <Details /> useful, but be careful with numbers. count && <List /> renders 0 when count is zero. Write count > 0 && <List /> when that is the real condition.

Keep expressions readable. Calculate a complex value before the JSX and give it a clear name.

You can call functions inside braces too: {formatDate(publishedAt)}. Keep the function pure so rendering stays predictable.

Attribute values also accept expressions: <img alt={name} width={size} />. The attribute name stays plain text; only the value goes inside braces.

Template literals work inside braces: `{firstName} ${lastName}`. You can mix static text and expressions in one JSX text node.

Map inside JSX when you need a list: {items.map(item => <li key={item.id}>{item.title}</li>)}. The map expression returns an array of elements React can render.

An empty string renders nothing visible, but it is different from null when you inspect the DOM node.

Try rendering the values 0, false, null, and an empty string. Inspect what appears in the DOM.

Lesson completed