How do you embed a JavaScript expression inside JSX?
Short answer
You wrap any JavaScript expression in a single pair of curly braces directly inside your JSX. This lets you display variables, call functions, or run small calculations right where you want the result to appear on the screen.
Advertisement
AModel answer
You wrap any JavaScript expression in a single pair of curly braces directly inside your JSX. This lets you display variables, call functions, or run small calculations right where you want the result to appear on the screen.
function Total({ price, quantity }) {
return <p>Total: ${price * quantity}</p>;
}
<Total price={10} quantity={3} /> // shows: Total: $30Real-world example
A shopping cart component uses curly braces to calculate and display the total price of an item directly inside the JSX, updating automatically whenever the quantity changes.
Likely follow-ups
- Can you put an if statement directly inside curly braces in JSX?
- What happens if you try to display a plain JavaScript object inside JSX?
Related topics