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>
You can use variables, property access, function calls, array methods, and conditional expressions.
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>
}
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.
Try rendering the values 0, false, null, and an empty string. Inspect what appears in the DOM.
Lesson completed