A common mistake in React is trying to assign variables or execute JavaScript expressions directly in JSX without using the required curly braces {}
. Here’s how to properly handle variable assignment and JavaScript expressions in JSX.
The Problem
function Component() {
return (
<div>
const message = "Hello"; // ❌ Error: Can't assign variables directly
<p>{message}</p>
</div>
);
}
Correct Approaches
1. Assign Variables Before Return
function Component() {
const message = "Hello"; // ✅ Correct variable assignment
return (
<div>
<p>{message}</p>
</div>
);
}
2. Use Immediately-Invoked Function Expression (IIFE)
function Component() {
return (
<div>
{(() => {
const message = "Hello"; // ✅ Works inside {}
return <p>{message}</p>;
})()}
</div>
);
}
3. Ternary Operator for Conditional Assignment
function Component({ isLoggedIn }) {
return (
<div>
<p>{isLoggedIn ? "Welcome back!" : "Please log in"}</p>
</div>
);
}
What Works in JSX Without Braces
Only these can appear directly in JSX without curly braces:
- String literals (
"text"
) - Numeric literals (
42
) - JSX elements (
<Component />
) - Arrays of JSX elements
true
,false
,null
,undefined
(render nothing)
Common Mistakes and Fixes
❌ Incorrect: Direct assignment
<div>
let count = 0; // Error
<p>{count}</p>
</div>
✅ Correct: Move assignment outside
let count = 0; // Outside JSX
function Component() {
return <p>{count}</p>;
}
❌ Incorrect: Block statement
<div>
{
let x = 10; // Error: block statements not allowed
x * 2
}
</div>
✅ Correct: Wrap in self-executing function
<div>
{(() => {
let x = 10;
return x * 2;
})()}
</div>
When You Need Complex Logic
For complex logic, extract it to a separate function:
function calculateValue() {
// Complex calculations here
return result;
}
function Component() {
return <div>{calculateValue()}</div>;
}
Key Rules to Remember
- JSX is not JavaScript – It gets transpiled to
React.createElement()
calls - Curly braces
{}
are required for any JavaScript expressions - Variable declarations must happen outside JSX or inside self-contained expressions
- Keep JSX clean – Move complex logic outside the return statement
Practical Example
Before (Error):
function UserList({ users }) {
return (
<ul>
users.map(user => ( // ❌ Missing {} and can't use statement
<li key={user.id}>{user.name}</li>
))
</ul>
);
}
After (Fixed):
function UserList({ users }) {
return (
<ul>
{users.map(user => ( // ✅ Wrapped in {}
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Remember: JSX is syntactic sugar for function calls, not a full JavaScript environment. Always use curly braces for JavaScript expressions and keep variable assignments outside your JSX markup.