React JSX Expressions
Embedding JavaScript in JSX
💡 What are JSX Expressions?
JSX expressions let you embed JavaScript code inside JSX using curly braces {}. You can use variables, perform calculations, call functions, and display dynamic content, making your React components interactive and data-driven.
// Using JavaScript in JSX
const name = "React";
const element = <h1>Hello, {name}!</h1>;
Output:
Hello, React!
Expression Types
Variables
Display variable values
<h1>{userName}</h1>
Math Operations
Perform calculations
<p>{5 + 10}</p>
Functions
Call functions for dynamic content
<p>{getName()}</p>
Ternary Operators
Conditional rendering
{isLoggedIn ? 'Hi' : 'Login'}
🔹 Using Variables
You can display any JavaScript variable inside JSX by wrapping it in curly braces. This makes your components dynamic, showing different content based on variable values.
// String Variables
const name = "Alice";
const greeting = <h1>Hello, {name}!</h1>;
// Number Variables
const age = 25;
const info = <p>Age: {age}</p>;
// Boolean (won't display directly)
const isActive = true;
const status = <p>Active: {isActive.toString()}</p>;
// Object Properties
const user = {name: "Bob", age: 30};
const profile = <h2>{user.name} is {user.age}</h2>;
Output:
Hello, Alice!
Age: 25
Active: true
Bob is 30
🔹 Mathematical Expressions
Perform calculations directly in JSX using curly braces. You can add, subtract, multiply, divide, and use any JavaScript math operations to display computed values dynamically.
// Basic Math
const sum = <p>5 + 3 = {5 + 3}</p>;
const product = <p>4 × 7 = {4 * 7}</p>;
// Using Variables
const price = 100;
const tax = 0.15;
const total = <p>Total: ${price + (price * tax)}</p>;
// Complex Calculations
const radius = 5;
const area = <p>Area: {Math.PI * radius * radius}</p>;
// Rounding Numbers
const value = 3.14159;
const rounded = <p>{value.toFixed(2)}</p>;
Output:
5 + 3 = 8
4 × 7 = 28
Total: $115
Area: 78.53981633974483
3.14
🔹 Calling Functions
Call JavaScript functions inside JSX to generate dynamic content. Functions can return strings, numbers, or even JSX elements, giving you powerful ways to create reusable logic.
// Simple Function
function getGreeting() {
return "Welcome back!";
}
const message = <h1>{getGreeting()}</h1>;
// Function with Parameters
function formatName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
const fullName = <p>{formatName("John", "Doe")}</p>;
// Function Returning JSX
function getTime() {
const hour = new Date().getHours();
return hour < 12 ? "Good Morning" : "Good Evening";
}
const greeting = <h2>{getTime()}</h2>;
Output:
Welcome back!
John Doe
Good Evening
🔹 String Methods
Use JavaScript string methods inside JSX expressions to manipulate text. You can convert case, extract parts of strings, replace text, and format content dynamically.
// String Methods
const text = "hello react";
const uppercase = <p>{text.toUpperCase()}</p>;
const capitalized = <p>{text.charAt(0).toUpperCase() + text.slice(1)}</p>;
const length = <p>Length: {text.length}</p>;
// Template Literals
const name = "Sarah";
const age = 28;
const bio = <p>{`My name is ${name} and I'm ${age} years old`}</p>;
// String Replacement
const message = "Hello World";
const updated = <p>{message.replace("World", "React")}</p>;
Output:
HELLO REACT
Hello react
Length: 11
My name is Sarah and I'm 28 years old
Hello React
🔹 Ternary Operators
Use ternary operators for simple conditional rendering in JSX. They're perfect for showing different content based on conditions, like displaying user status or toggling between two states.
// Basic Ternary
const isLoggedIn = true;
const message = <p>{isLoggedIn ? "Welcome back!" : "Please login"}</p>;
// With Variables
const age = 20;
const status = <p>{age >= 18 ? "Adult" : "Minor"}</p>;
// Nested Ternary
const score = 85;
const grade = (
<p>
Grade: {score >= 90 ? "A" : score >= 80 ? "B" : "C"}
</p>
);
// With Components
const hasAccess = true;
const content = <div>{hasAccess ? <Dashboard /> : <Login />}</div>;
Output:
Welcome back!
Adult
Grade: B
🔹 Array Methods
Use array methods like map, filter, and join inside JSX to work with lists of data. These methods help you transform arrays into JSX elements dynamically.
// Array Join
const fruits = ["Apple", "Banana", "Orange"];
const list = <p>{fruits.join(", ")}</p>;
// Array Length
const items = [1, 2, 3, 4, 5];
const count = <p>Total items: {items.length}</p>;
// Array Index Access
const colors = ["red", "green", "blue"];
const first = <p>First color: {colors[0]}</p>;
// Array Methods
const numbers = [1, 2, 3, 4, 5];
const sum = <p>Sum: {numbers.reduce((a, b) => a + b, 0)}</p>;
Output:
Apple, Banana, Orange
Total items: 5
First color: red
Sum: 15