How do you use JavaScript expressions inside JSX, and what cannot go inside the braces?
Curly braces accept any JavaScript expression: a variable, a function call, a ternary. Statements such as if, for or switch are not expressions, so they must live outside the JSX.
Explain it simply
Curly braces are a window from the markup into JavaScript. Whatever sits in the window must produce a value, because React puts that value on the screen.
{price * 2}, {user.name} and {isOpen ? "Open" : "Closed"} all produce values. An if block does not produce a value, so it cannot go in the braces. Do the if before the return, or use a ternary or &&.
Example
function Fare({ km, isStudent }) {
const base = km * 2;
return (
<p>
Fare: Rs {isStudent ? base / 2 : base}
{km > 500 && <span> (long route)</span>}
</p>
);
}
// Fare km=100 isStudent=true renders: Fare: Rs 100Objects work too, but note the double braces in style={{ color: "red" }}: the outer pair opens JavaScript, the inner pair is the object.
What to say in the interview
"Braces in JSX take any expression, such as variables, calls, ternaries and logical AND. Statements like if or for are not allowed, so I compute the value above the return or use a ternary. The double braces in style are just an object literal inside the expression braces."
Common mistakes
- Writing if (...) { } directly inside the braces.
- Rendering a plain object as a child, which throws an error.