One of the main reasons JSX is so powerful is that it allows JavaScript to work directly with the UI.
JSX looks like HTML, but it is written inside JavaScript. Because of this, you can use JavaScript values, calculations, object properties, function calls, conditions, and array methods while creating your React interface.
For example:
function App() {
const name = "John";
return <h1>Hello, {name}!</h1>;
}
Here, {name} connects the JavaScript variable with the JSX.
This makes it possible to build interfaces that respond to changing data instead of displaying only fixed content.
How JavaScript Works Inside JSX
JavaScript expressions are inserted into JSX using curly braces {}.
<h1>{name}</h1>
The curly braces tell React that the content inside them should be treated as JavaScript.
For example:
function App() {
const name = "Arafat";
const age = 25;
return (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
</div>
);
}
The JSX structure creates the elements, while JavaScript provides the dynamic values.
You can think of the relationship like this:
JavaScript Data
↓
{Expression}
↓
JSX
↓
React UI
Using JavaScript Variables
Variables are one of the most common ways to bring JavaScript data into JSX.
function App() {
const username = "John";
const role = "Frontend Developer";
return (
<div>
<h1>{username}</h1>
<p>{role}</p>
</div>
);
}
React evaluates the expressions and displays their values.
You can use variables for:
- Names
- Prices
- Messages
- Numbers
- Status values
- URLs
- Boolean values
- Objects
- Arrays
For example:
const price = 2500;
const quantity = 2;
return <p>Total: ₹{price * quantity}</p>;
The calculation happens in JavaScript before the result is displayed.
Using JavaScript Calculations
JavaScript arithmetic can be used directly inside JSX.
function App() {
const price = 1000;
const quantity = 3;
return (
<h2>Total: ₹{price * quantity}</h2>
);
}
You can use operators such as:
+
-
*
/
%
For example:
<p>{10 + 20}</p>
<p>{50 - 10}</p>
<p>{5 * 4}</p>
<p>{100 / 2}</p>
<p>{10 % 3}</p>
For simple calculations, placing the expression directly in JSX is fine.
For more complicated calculations, it is usually cleaner to calculate the value first.
const subtotal = price * quantity;
const discount = subtotal * 0.1;
const total = subtotal - discount;
return <p>Total: ₹{total}</p>;
This keeps the JSX easier to read.
Using JavaScript Strings
Strings can be displayed using JavaScript variables.
const firstName = "John";
const lastName = "Smith";
return (
<h1>
{firstName} {lastName}
</h1>
);
You can also use string methods.
const name = "react";
return <h1>{name.toUpperCase()}</h1>;
The result is:
REACT
Another example:
const message = "Learn React";
return <p>{message.length} characters</p>;
JavaScript handles the operation, and JSX displays the result.
Using JavaScript Objects
Objects are commonly used to store related information.
function App() {
const user = {
name: "John",
age: 25,
role: "Developer"
};
return (
<div>
<h2>{user.name}</h2>
<p>{user.age}</p>
<p>{user.role}</p>
</div>
);
}
You can access object properties using dot notation:
{user.name}
{user.age}
{user.role}
You can also use bracket notation:
{user["name"]}
Nested objects can also be accessed:
const user = {
profile: {
name: "John",
city: "Hyderabad"
}
};
return <p>{user.profile.city}</p>;
This becomes especially useful when working with API responses.
Using JavaScript Arrays
Arrays can be used inside JSX expressions.
const fruits = ["Apple", "Banana", "Mango"];
return <p>{fruits.join(", ")}</p>;
For rendering individual items, .map() is commonly used.
const fruits = ["Apple", "Banana", "Mango"];
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
The JavaScript .map() method creates a JSX element for each item.
This pattern is fundamental to React because many applications display lists of data.
Using JavaScript Functions
Functions can be called from JSX when their returned value needs to be displayed.
function getGreeting() {
return "Welcome to React!";
}
function App() {
return <h1>{getGreeting()}</h1>;
}
You can also pass values to functions.
function formatPrice(price) {
return `₹${price}`;
}
function App() {
const price = 2500;
return <p>{formatPrice(price)}</p>;
}
The function performs the JavaScript operation, and JSX displays the returned value.
Using Conditional JavaScript
JavaScript conditions are commonly used to control what appears in a React interface.
A ternary expression can be used directly inside JSX:
function App() {
const isLoggedIn = true;
return (
<h1>
{isLoggedIn ? "Welcome back!" : "Please log in"}
</h1>
);
}
You can also use && when content should appear only when a condition is true.
const isAdmin = true;
return (
<div>
{isAdmin && <p>Admin Dashboard</p>}
</div>
);
For more complicated conditions, perform the logic before the JSX.
let message;
if (age >= 18) {
message = "You can access this page.";
} else {
message = "You cannot access this page.";
}
return <p>{message}</p>;
This keeps complicated JavaScript logic outside the JSX markup.
JavaScript if Statements and JSX
A common beginner mistake is trying to put an if statement directly inside JSX.
This does not work:
return (
<h1>
{if (isLoggedIn) {
"Welcome";
}}
</h1>
);
An if statement is a JavaScript statement, not an expression that can be placed directly inside {}.
Instead, use a ternary expression:
return (
<h1>
{isLoggedIn ? "Welcome" : "Please log in"}
</h1>
);
Or perform the if statement before returning JSX:
let message;
if (isLoggedIn) {
message = "Welcome";
} else {
message = "Please log in";
}
return <h1>{message}</h1>;
Both approaches are valid.
Using JavaScript in JSX Attributes
JavaScript can also control JSX attributes.
For example:
const imageUrl = "/images/logo.png";
return <img src={imageUrl} />;
Another example:
const isDisabled = true;
return (
<button disabled={isDisabled}>
Submit
</button>
);
You can also calculate an attribute value:
const width = 200;
return <img src={imageUrl} width={width} />;
This makes attributes dynamic.
Using JavaScript for Dynamic Class Names
JavaScript can determine which CSS class should be applied.
const isActive = true;
return (
<button className={isActive ? "active" : "inactive"}>
Profile
</button>
);
If isActive is true, the button receives:
active
Otherwise, it receives:
inactive
This is useful for navigation menus, selected tabs, buttons, alerts, and other interactive UI elements.
Using JavaScript for Inline Styles
JavaScript objects can be used for dynamic inline styles.
const textColor = "blue";
return (
<h1 style={{ color: textColor }}>
Hello React
</h1>
);
You can also calculate style values.
const size = 20;
return (
<p style={{ fontSize: `${size}px` }}>
Dynamic text
</p>
);
The outer curly braces tell JSX that JavaScript is being used.
The inner curly braces represent the JavaScript style object.
Using JavaScript Expressions in Multiple Places
A single JSX element can contain JavaScript expressions in several locations.
function App() {
const user = {
name: "John",
age: 25
};
const imageUrl = "/profile.jpg";
return (
<div className="profile">
<img src={imageUrl} alt={user.name} />
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
<p>{user.age >= 18 ? "Adult" : "Minor"}</p>
</div>
);
}
Here JavaScript is being used for:
- The image URL
- The image
altvalue - The user’s name
- The user’s age
- The conditional message
This is one of the main ways React components become data-driven.
Using JavaScript Methods
JavaScript methods can be called inside JSX.
For strings:
const name = "john";
return <h1>{name.toUpperCase()}</h1>;
For arrays:
const numbers = [10, 20, 30];
return <p>{numbers.join(" - ")}</p>;
For calculations:
const price = 500;
return <p>{price.toFixed(2)}</p>;
You can use JavaScript’s built-in methods as long as the resulting value can be used appropriately by React.
Using Optional Chaining
When working with data that may not exist yet, optional chaining can help safely access nested properties.
const user = {};
return <h2>{user.profile?.name}</h2>;
Without optional chaining, accessing user.profile.name when profile is missing could cause an error.
You can also provide a fallback:
return (
<h2>
{user.profile?.name ?? "Guest"}
</h2>
);
This pattern is particularly useful when data comes from an API and may initially be unavailable.
Using JavaScript Date Values
JavaScript objects and methods can also be used to generate dynamic content.
const currentYear = new Date().getFullYear();
return <p>© {currentYear} My Website</p>;
The JavaScript expression calculates the current year, and JSX displays it.
You can also format dates before displaying them:
const date = new Date();
return <p>{date.toLocaleDateString()}</p>;
Using Boolean Values
Boolean variables can control the UI.
const isOnline = true;
return (
<p>
Status: {isOnline ? "Online" : "Offline"}
</p>
);
Boolean values are especially useful for:
- Login status
- Loading states
- Visibility
- Permissions
- Availability
- Selected items
- Feature states
For example:
const isLoading = false;
return (
<div>
{isLoading ? <p>Loading...</p> : <p>Content loaded.</p>}
</div>
);
JavaScript Inside JSX vs JavaScript Outside JSX
JavaScript can be used both inside and outside JSX.
Use JSX expressions for simple dynamic values:
return <h1>Hello, {name}</h1>;
Use JavaScript before the return for more complicated logic:
const fullName = `${firstName} ${lastName}`;
const total = price * quantity;
return (
<div>
<h1>{fullName}</h1>
<p>Total: ₹{total}</p>
</div>
);
This separation can make your components easier to understand.
A good general approach is:
Simple value
↓
Use directly in JSX
Complex calculation or logic
↓
Calculate before return
↓
Use result in JSX
JavaScript Statements Should Usually Stay Outside JSX
JSX is designed to work with JavaScript expressions, not arbitrary statements.
For example, keep this outside the JSX:
const total = price * quantity;
if (total > 5000) {
console.log("Large order");
}
Then use the resulting values inside JSX:
return (
<div>
<p>Total: ₹{total}</p>
{total > 5000 && <p>Large order</p>}
</div>
);
This keeps the UI structure readable while JavaScript handles the logic.
A Complete Example
The following example demonstrates several ways JavaScript can work inside JSX:
function ProductCard() {
const product = {
name: "Wireless Headphones",
price: 2500,
quantity: 2,
inStock: true
};
const total = product.price * product.quantity;
function formatPrice(price) {
return `₹${price.toLocaleString("en-IN")}`;
}
return (
<div className="product-card">
<h2>{product.name}</h2>
<p>Price: {formatPrice(product.price)}</p>
<p>Quantity: {product.quantity}</p>
<p>Total: {formatPrice(total)}</p>
{product.inStock ? (
<p>Available</p>
) : (
<p>Out of stock</p>
)}
{product.quantity > 1 && (
<p>Multiple items selected.</p>
)}
<button disabled={!product.inStock}>
Buy Now
</button>
</div>
);
}
This component uses JavaScript for:
| JavaScript feature | Example |
|---|---|
| Object | product |
| Property access | product.name |
| Calculation | product.price * product.quantity |
| Function | formatPrice() |
| Method | toLocaleString() |
| Ternary | product.inStock ? ... : ... |
&& | product.quantity > 1 && ... |
| Boolean | product.inStock |
| Attribute expression | disabled={!product.inStock} |
JSX is responsible for describing the UI, while JavaScript provides the data and logic that make that UI dynamic.
Common Mistakes
Writing a Variable Without Curly Braces
Incorrect:
<h1>name</h1>
This displays the word name.
Correct:
<h1>{name}</h1>
Putting a JavaScript Expression Inside Quotes
Incorrect:
<img src="{imageUrl}" />
Correct:
<img src={imageUrl} />
Quotes create a string value. Curly braces tell JSX to evaluate JavaScript.
Putting an if Statement Directly Inside JSX
Incorrect:
<p>{if (age >= 18) "Adult"}</p>
Use:
<p>{age >= 18 ? "Adult" : "Minor"}</p>
Or calculate the value before the return.
Rendering an Object Directly
Avoid:
<p>{user}</p>
Instead, access a property:
<p>{user.name}</p>
Making JSX Too Complex
Avoid putting large amounts of JavaScript logic directly inside JSX.
Instead of:
<p>
{user &&
user.profile &&
user.profile.account &&
user.profile.account.name
? user.profile.account.name.toUpperCase()
: "Guest"}
</p>
prepare the value first:
const name =
user?.profile?.account?.name?.toUpperCase() ?? "Guest";
return <p>{name}</p>;
The second version is easier to read and maintain.
Where to Place an Image
Image Placement: After “How JavaScript Works Inside JSX”
Create a 16:9 React infographic showing JavaScript data flowing into JSX through curly braces.
Visual flow:
JavaScript
Variables
Objects
Functions
Calculations
Conditions
↓
{ ... }
↓
JSX
↓
React UI
Show a small code example such as {user.name} transforming into visible UI text.
Caption:
JavaScript expressions connect dynamic data and logic with JSX UI.
Alt text:
React infographic showing JavaScript variables, objects, functions, and expressions being inserted into JSX using curly braces.
Practice Exercise
Create a StudentCard component using this JavaScript object:
const student = {
name: "Alex",
course: "React Development",
age: 22,
score: 85,
isOnline: true
};
Use JavaScript inside JSX to display:
- Student name
- Course
- Age
- Score
- Online or offline status
- Whether the student passed
- A message if the score is greater than 80
For the pass/fail status, use a ternary expression.
For the online message, try using &&.
Also create a function that formats the student’s name:
function formatName(name) {
return name.toUpperCase();
}
Then use that function inside JSX.
Key Takeaways
JavaScript inside JSX is what makes React interfaces dynamic and data-driven.
Remember these important points:
- Use
{}to insert JavaScript expressions into JSX. - Variables can be displayed directly inside JSX.
- Calculations can be performed using JavaScript expressions.
- Object properties can be accessed inside JSX.
- Functions can be called to transform or format values.
- Arrays can be processed using methods such as
.map(). - Ternary expressions can handle conditional content.
&&can conditionally display JSX.- JavaScript can dynamically control JSX attributes.
- JavaScript objects can be used for inline styles.
if,for, and similar statements should not be placed directly inside JSX expression positions.- Complex logic is usually cleaner when calculated before the
return. - Optional chaining and nullish coalescing are useful when working with potentially missing data.
The key idea is simple:
JavaScript
+
JSX
=
Dynamic React UI
Once you understand how JavaScript works inside JSX, the next important step is learning how to use variables in JSX to organize and display dynamic data cleanly.