One of the most useful features of JSX is the ability to use JavaScript expressions directly inside your UI.
JSX allows you to combine markup-like syntax with JavaScript values, calculations, function calls, object properties, conditions, and other expressions. This makes React interfaces dynamic instead of limited to static content.
For example:
function App() {
const name = "John";
return <h1>Hello, {name}!</h1>;
}
Here, {name} is a JSX expression. React evaluates the JavaScript expression and displays its result.
What Is a JSX Expression?
A JSX expression is a JavaScript expression written inside curly braces {}.
The curly braces tell JSX:
“Evaluate the JavaScript inside here and use its result.”
For example:
<h1>{name}</h1>
If:
const name = "John";
React renders:
Hello, John
You can use many types of JavaScript expressions inside JSX.
<p>{10 + 20}</p>
<p>{user.name}</p>
<p>{price * quantity}</p>
<p>{isLoggedIn ? "Welcome" : "Login"}</p>
Using Variables in JSX Expressions
Variables are one of the most common things you’ll place inside JSX expressions.
function App() {
const name = "Arafat";
const age = 25;
return (
<div>
<h1>Hello, {name}</h1>
<p>Age: {age}</p>
</div>
);
}
The variables are evaluated and their values are inserted into the rendered UI.
This allows your components to display dynamic information.
Using Numbers in JSX Expressions
Numbers can be placed directly inside curly braces.
function App() {
return (
<div>
<p>{10}</p>
<p>{25 + 5}</p>
<p>{100 / 4}</p>
</div>
);
}
The rendered result is:
10
30
25
You can also calculate values before displaying them.
const price = 500;
const quantity = 3;
return <p>Total: ₹{price * quantity}</p>;
The result is:
Total: ₹1500
Performing Calculations Inside JSX
JavaScript arithmetic expressions can be used directly inside JSX.
function App() {
const price = 100;
const quantity = 4;
return (
<h2>Total: ₹{price * quantity}</h2>
);
}
You can use operators such as:
+
-
*
/
%
For example:
<p>{10 + 5}</p>
<p>{20 - 8}</p>
<p>{6 * 7}</p>
<p>{100 / 5}</p>
<p>{10 % 3}</p>
For complicated calculations, however, it is usually cleaner to calculate the value in a variable before the return.
const subtotal = price * quantity;
const tax = subtotal * 0.18;
const total = subtotal + tax;
return <p>Total: ₹{total}</p>;
This keeps the JSX easier to read.
Accessing Object Properties
You can access object properties inside JSX expressions.
function App() {
const user = {
name: "John",
age: 28,
role: "Developer"
};
return (
<div>
<h1>{user.name}</h1>
<p>Age: {user.age}</p>
<p>Role: {user.role}</p>
</div>
);
}
Here:
{user.name}
and:
{user.role}
are JavaScript expressions.
You can also access nested properties:
const user = {
profile: {
name: "John"
}
};
return <h1>{user.profile.name}</h1>;
Calling Functions Inside JSX
Function calls are expressions, so they can be used inside JSX.
function getGreeting() {
return "Welcome to React!";
}
function App() {
return <h1>{getGreeting()}</h1>;
}
React evaluates:
getGreeting()
and displays the returned value.
Another example:
function formatName(name) {
return name.toUpperCase();
}
function App() {
return <h1>{formatName("John")}</h1>;
}
The result is:
JOHN
This can be useful for formatting or transforming data before displaying it.
Using String Methods
JavaScript string methods can also be used.
const name = "react";
return <h1>{name.toUpperCase()}</h1>;
You can also use:
const message = "Learn React";
return <p>{message.length}</p>;
Or:
const name = "John";
return <p>{name.charAt(0)}</p>;
Because these are JavaScript expressions, they can be evaluated inside {}.
Using Template Literals
Template literals can be used inside JSX expressions.
const name = "John";
return <h1>{`Hello, ${name}!`}</h1>;
However, for simple JSX, you often don’t need a template literal.
This is usually cleaner:
<h1>Hello, {name}!</h1>
Use template literals when you actually need to construct a more complex string.
Using Boolean Expressions
Boolean expressions can be evaluated inside JSX.
const age = 25;
return <p>{age >= 18}</p>;
This evaluates to:
true
However, displaying raw boolean values is not usually useful.
Boolean expressions become much more useful for conditional rendering.
const isLoggedIn = true;
return (
<div>
{isLoggedIn && <p>Welcome back!</p>}
</div>
);
If isLoggedIn is true, the paragraph is rendered.
Using Ternary Expressions
The ternary operator is one of the most common expressions used in JSX.
The syntax is:
condition ? valueIfTrue : valueIfFalse
For example:
const isLoggedIn = true;
return (
<h1>
{isLoggedIn ? "Welcome back!" : "Please log in"}
</h1>
);
If isLoggedIn is true, React displays:
Welcome back!
If it is false, React displays:
Please log in
You can also return JSX from each side:
return (
<div>
{isLoggedIn ? (
<button>Logout</button>
) : (
<button>Login</button>
)}
</div>
);
Using the Logical AND Operator
The && operator is commonly used when something should appear only when a condition is true.
const isAdmin = true;
return (
<div>
{isAdmin && <p>Admin Dashboard</p>}
</div>
);
When isAdmin is true, the paragraph appears.
When it is false, React renders nothing for that expression.
Another example:
const hasMessages = true;
return (
<div>
{hasMessages && <p>You have new messages.</p>}
</div>
);
This is useful for simple conditional UI.
Using the OR Operator
The logical OR operator can provide a fallback value.
const username = "";
return <h1>{username || "Guest"}</h1>;
If username is empty, the expression evaluates to "Guest".
Another example:
const title = product.title || "Untitled Product";
return <h2>{title}</h2>;
This can be useful when data may be missing.
Be aware that || treats several values as falsy, including 0, "", false, null, and undefined. If 0 is a valid value that should be displayed, a nullish check such as ?? may be more appropriate.
const quantity = 0;
return <p>{quantity ?? "Not available"}</p>;
Using the Nullish Coalescing Operator
The ?? operator provides a fallback only when the value is null or undefined.
const username = null;
return <h1>{username ?? "Guest"}</h1>;
This is different from ||.
For example:
const quantity = 0;
return <p>{quantity ?? 10}</p>;
The result is:
0
because 0 is not null or undefined.
Using Arrays in JSX Expressions
Arrays can be used inside JSX expressions.
const fruits = ["Apple", "Banana", "Mango"];
return <p>{fruits.join(", ")}</p>;
The result is:
Apple, Banana, Mango
Arrays are particularly useful when rendering lists.
const fruits = ["Apple", "Banana", "Mango"];
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
The .map() callback produces JSX for each item.
Using Array Methods
JavaScript array methods can be used as JSX expressions.
For example:
const numbers = [10, 20, 30];
return <p>{numbers.length}</p>;
You can also use methods such as:
numbers.join(", ")
numbers.map(...)
numbers.filter(...)
numbers.includes(...)
For example:
const products = ["Laptop", "Phone", "Tablet"];
return (
<ul>
{products.map((product) => (
<li key={product}>{product}</li>
))}
</ul>
);
This is an important pattern in React because application data is frequently represented as arrays.
Using Comparison Operators
Comparison expressions can also be used.
const age = 21;
return <p>{age >= 18 ? "Adult" : "Minor"}</p>;
Other comparison operators include:
>
<
>=
<=
===
!==
For example:
const score = 85;
return (
<p>
{score >= 50 ? "Passed" : "Failed"}
</p>
);
Using Logical Operators
JavaScript logical operators can be useful inside JSX.
const isLoggedIn = true;
const isAdmin = false;
return (
<div>
{isLoggedIn && <p>Logged in</p>}
{isAdmin && <p>Administrator</p>}
</div>
);
You can combine conditions as well:
const age = 25;
const hasPermission = true;
return (
<p>
{age >= 18 && hasPermission ? "Access granted" : "Access denied"}
</p>
);
For complicated conditions, it is usually better to calculate the result in a variable first.
const canAccess = age >= 18 && hasPermission;
return (
<p>
{canAccess ? "Access granted" : "Access denied"}
</p>
);
Expressions Can Be Used in JSX Attributes
JSX expressions are not limited to text content. They can also provide dynamic attribute values.
const imageUrl = "/images/profile.png";
return <img src={imageUrl} />;
Another example:
const buttonDisabled = true;
return (
<button disabled={buttonDisabled}>
Submit
</button>
);
You can also use expressions:
const width = 300;
return <img src={imageUrl} width={width} />;
This allows attributes to change based on variables and application data.
Expressions Can Be Used for Inline Styles
Inline styles in JSX use JavaScript objects.
const textColor = "blue";
return (
<h1 style={{ color: textColor }}>
Hello React
</h1>
);
The outer {} tells JSX that a JavaScript expression is being used.
The inner {} represents the JavaScript object.
For example:
style={{ color: "blue", fontSize: "20px" }}
This concept becomes important when working with inline styling in React.
What Cannot Be Used Directly as a JSX Expression?
JSX expects expressions inside curly braces.
You can use:
{name}
{user.age}
{price * quantity}
{isLoggedIn ? "Logout" : "Login"}
But you cannot directly place statements such as if, for, or while inside the JSX expression position.
For example, this is invalid:
return (
<div>
{if (isLoggedIn) {
"Welcome";
}}
</div>
);
Instead, use an expression:
return (
<div>
{isLoggedIn ? "Welcome" : "Please log in"}
</div>
);
Or perform the logic before the return:
let message;
if (isLoggedIn) {
message = "Welcome";
} else {
message = "Please log in";
}
return <h1>{message}</h1>;
JavaScript Statements vs Expressions
Understanding the difference between statements and expressions is important when working with JSX.
An expression produces a value.
Examples:
name
10 + 20
user.name
price * quantity
isLoggedIn ? "Yes" : "No"
getUsername()
A statement performs an action or controls program flow.
Examples:
if (...)
for (...)
const name = "John";
return ...
JSX curly braces are designed for JavaScript expressions.
For example:
<h1>{name}</h1>
works because name is an expression.
Expressions Can Return JSX
A JavaScript expression can itself produce JSX.
For example:
const isLoggedIn = true;
const content = isLoggedIn
? <h1>Welcome back!</h1>
: <h1>Please log in.</h1>;
return <div>{content}</div>;
You can also use a function:
function getMessage() {
return <p>Welcome to React!</p>;
}
function App() {
return (
<div>
{getMessage()}
</div>
);
}
The function returns JSX, which is then inserted into the component.
A Practical JSX Expressions Example
Here is an example that combines several expressions:
function Product() {
const product = {
name: "Laptop",
price: 60000,
quantity: 2,
inStock: true
};
const total = product.price * product.quantity;
return (
<div className="product">
<h2>{product.name}</h2>
<p>Price: ₹{product.price}</p>
<p>Quantity: {product.quantity}</p>
<p>Total: ₹{total}</p>
{product.inStock ? (
<p>Available</p>
) : (
<p>Out of stock</p>
)}
{product.quantity > 1 && (
<p>You ordered multiple items.</p>
)}
</div>
);
}
This example uses:
- Object property expressions
- Arithmetic expressions
- Variables
- Ternary expressions
&&- JSX inside expressions
- Dynamic text
- Dynamic class attributes
Where to Place an Image
Image Placement: After “What Is a JSX Expression?”
Create a 16:9 modern React infographic showing:
JavaScript Expression
↓
{ value }
↓
JSX
↓
React UI
Around the {} symbol, show examples such as name, 10 + 20, user.name, and isLoggedIn ? ... : ....
Caption:
JSX uses curly braces to evaluate JavaScript expressions and display their results.
Alt text:
JSX expressions infographic showing JavaScript values inside curly braces being rendered into a React interface.
Practice Exercise
Create a ProductCard component with the following data:
const product = {
name: "Wireless Headphones",
price: 2500,
quantity: 2,
inStock: true
};
Use JSX expressions to display:
- Product name
- Product price
- Quantity
- Total price
- Stock status
- A message when the quantity is greater than one
Try to use:
{product.name}
{product.price * product.quantity}
and a ternary expression for the stock status.
Then add a condition using && to display the multiple-item message.
Common Mistakes
Forgetting Curly Braces
Incorrect:
<h1>name</h1>
Correct:
<h1>{name}</h1>
Putting a Variable Inside Quotes
Incorrect:
<img src="imageUrl" />
Correct:
<img src={imageUrl} />
Trying to Use if Directly Inside JSX
Incorrect:
<p>{if (isLoggedIn) "Welcome"}</p>
Correct:
<p>{isLoggedIn ? "Welcome" : "Please log in"}</p>
Rendering an Object Directly
Avoid:
<p>{user}</p>
Instead:
<p>{user.name}</p>
Making JSX Too Complicated
Although JSX expressions can contain JavaScript logic, putting too much logic directly inside JSX can make components difficult to understand.
Instead of:
<p>
{user && user.profile && user.profile.name
? user.profile.name.toUpperCase()
: "Unknown"}
</p>
you can prepare the value first:
const userName = user?.profile?.name?.toUpperCase() ?? "Unknown";
return <p>{userName}</p>;
Keeping expressions simple generally makes JSX easier to maintain.
JSX Expressions Cheat Sheet
| Expression | Example | Purpose |
|---|---|---|
| Variable | {name} | Display a value |
| Calculation | {price * quantity} | Calculate values |
| Property | {user.name} | Access object data |
| Function | {getName()} | Use a returned value |
| Ternary | {condition ? "Yes" : "No"} | Conditional content |
| AND | {isAdmin && <Admin />} | Show content conditionally |
| OR | {name || "Guest"} | Provide a fallback |
| Nullish | {value ?? "N/A"} | Fallback for null/undefined |
| Array method | {items.map(...)} | Render collections |
| String method | {name.toUpperCase()} | Transform text |
Key Takeaways
JSX expressions are what allow React interfaces to work with dynamic JavaScript data.
Remember these important points:
- JSX expressions are written inside
{}. - Variables can be displayed directly in JSX.
- Calculations can be performed inside expressions.
- Object properties can be accessed inside JSX.
- Functions can be called when their returned value is needed.
- Ternary expressions are useful for conditional content.
&&is useful for simple conditional rendering.||and??can provide fallback values.- Arrays can be transformed into JSX using methods such as
.map(). - Expressions can also be used inside JSX attributes.
- JavaScript statements such as
ifandforcannot be placed directly where JSX expects an expression. - Complex logic is usually better calculated before the
return.
Once you understand JSX expressions, the next step is learning how to place regular JavaScript inside JSX, including variables, functions, calculations, and data manipulation.