Expressions and curly braces
- React course
- Beginner
- Lesson 6/84
- 4 min
Learn to put variables and expressions inside curly braces.
Expressions and curly braces
The strongest side of JSX is that you can put any JavaScript expression inside curly braces { }. Writing <p>{name}</p> makes React put the value of name there.
Inside the braces you can also use a function call, a math operation or a logical expression: <p>{ 5 + 3 }</p> or <p>{ format(date) }</p>.
Expressions must be a single line: statements like if cannot go inside braces; use the ternary operator cond ? a : b instead.
Nested expressions
You can even put JSX inside curly braces. For example, <main>{ isLoggedIn && <Avatar /> }</main> shows an avatar only when the user is logged in.
Array methods also work inside braces: <ul>{ items.map(i => <li>{i}</li>) }</ul> turns an array into list items. We'll explore this in the list rendering lesson.
If the expression inside the braces returns null, false or undefined, React renders nothing — handy for conditional rendering.
Practice Show a numeric expression
Complete the skeleton. Write a component called Total that shows the result of 10 + 5 inside a <p> using curly braces, and export it.
Starter code
// Write the Total component hereSample solution
function Total() {
return <p>{10 + 5}</p>;
}
export default Total;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Insert an expression
<p>Hello ____</p>
<p>Hello {name}</p>
Explanation: {name} embeds the value inside curly braces.
2 Which can go inside curly braces?
- { if (x) 1 }
- { 5 + 3 } Correct answer
- { for (i=0; i<3; i++) }
- { return 5; }
Explanation: 5 + 3 is an expression; if, for and return are statements.
3 Match the expression examples
| Term | Meaning |
|---|---|
{name} |
Variable |
{ 5 + 3 } |
Math |
{ format(d) } |
Call |
{ a && b } |
Logic |