CodeBlanks Logo Icon CodeBlanks

Expressions

Learn JavaScript expressions in JSX with {}.

Expressions in curly braces

In JSX, you use curly braces { } to embed a JavaScript expression. For example, <Text>Hello, {name}</Text> inserts the value of the name variable into the text.

Inside the braces you can put any expression: a variable, an arithmetic operation, array access, a function call. For instance, <Text>{1 + 2}</Text> prints 3.

However, statements like if do not work inside braces; you use a ternary instead.

Operations and functions

Curly braces do more than hold variables; they compute. With <Text>{price * 1.18}</Text> you can show a price including tax.

You can also embed a function result: <Text>{getLabel()}</Text>. The value returned by the function is displayed.

Array and object access also work: <Text>{user.name}</Text>. This flexibility makes JSX powerful.

Practice Embed an expression

Write an App component. Define a variable called userName (e.g. const userName = 'Alex';). Inside a <Text> use curly braces to concatenate Hello, and the userName value.

Starter code

App.js
// Define userName variable
// Write the App component
function App() {
  return null;
}

Sample solution

App.js
const userName = 'Alex';

function App() {
  return (
    <Text>Hello, {userName}</Text>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Embed a variable

Question
<Text>Hello, ____</Text>
Answer
<Text>Hello, {userName}</Text>

Explanation: A variable value is embedded inside curly braces.

2 What does {user.name} do?

App.js
<Text>{user.name}</Text>
  • Prints the full content of the user variable
  • Declares a new variable called name
  • Prints the value of the name property of the user object Correct answer
  • Assigns the name variable to user

Explanation: The dot accesses a property of the object.

3 Match the expression types

Term Meaning
{name} Variable
{1 + 2} Operation
{user.age} Property
{getLabel()} Function

All lessons in Beginner