Topic 5 of 54
Embedding JavaScript in JSX
Overview
One of the greatest powers of JSX is that it allows you to inject dynamic JavaScript expressions directly into your markup. You don't need a separate templating language like Handlebars or EJS. By wrapping your JS in curly braces `{}`, you can display variables, run functions, and perform mathematical operations right where the UI is defined.
Syntax
The curly braces `{}` open a 'window' to JavaScript land. Anything inside must be an expression (something that produces a value).
Using Variables and Expressions
jsx
function UserGreeting() {
const name = "Alice";
const age = 22;
const isOnline = true;
return (
<div className="card">
{/* 1. Displaying variables */}
<h1>Welcome, {name}!</h1>
{/* 2. Evaluating expressions */}
<p>Next year, you will be {age + 1}.</p>
{/* 3. Calling functions */}
<p>Uppercase Name: {name.toUpperCase()}</p>
{/* 4. Ternary operator for logic */}
<span className={isOnline ? 'text-green' : 'text-gray'}>
Status: {isOnline ? 'Online' : 'Offline'}
</span>
</div>
);
}Common Pitfalls
- Trying to use a standard if-statement inside JSX. You must use `&&` or ternary operators `? :`.
- Forgetting the double curly braces `{{}}` when passing inline styles to an element.
Interview Tips
- Remember that you can only put *expressions* inside `{}`. You cannot put *statements* (like if-else blocks or for-loops) directly inside JSX. You must use ternary operators or .map() instead.
Real-World Example
Generating inline styles dynamically based on state.
example
jsx
function ProgressBar({ progress }) {
// We use double curly braces {{}} for inline styles
// The outer {} is for JS mode, the inner {} is the actual style object
return (
<div className="progress-container">
<div
className="progress-bar"
style={{
width: `${progress}%`,
backgroundColor: progress === 100 ? 'green' : 'blue'
}}
/>
<p>{progress}% Complete</p>
</div>
);
}