Popular Searches
Popular Course Categories
Popular Courses

Embedding Expressions in JSX

Embedding Expressions in JSX

JSX in React

Embedding Expressions in JSX in React

1. Introduction to Embedding Expressions in JSX

Embedding expressions in JSX means using JavaScript expressions inside JSX markup to display dynamic content, perform calculations, access object properties, call functions and determine what appears in a React user interface.

JSX stands for JavaScript XML. It allows developers to write HTML-like markup inside JavaScript code. React uses JSX to describe the user interface, while curly braces {} allow JavaScript expressions to be included within that markup.

For example, instead of writing a fixed heading such as Hello, Student!, you can use a variable to display a person's name dynamically.

Basic Example

function App() {
  const name = "Rahul";
  return (
    <div>
      <h1>Hello, {name}!</h1>
    </div>
  );
}
export default App;

Output: Hello, Rahul!

In this example, {name} reads the value of the JavaScript variable and displays it inside the heading.


2. What Is a JavaScript Expression?

A JavaScript expression is a piece of code that produces a value. Expressions can return strings, numbers, Boolean values, calculations, object properties, function results and other values.

Examples of JavaScript expressions include:

  • 10 + 20 — produces the number 30.
  • "Hello" + " World" — produces the string Hello World.
  • name — reads the value of a variable.
  • student.name — accesses an object property.
  • isLoggedIn ? "Welcome" : "Login" — produces one of two values.
  • getMessage() — produces the return value of a function.

Example

function App() {
  const a = 10;
  const b = 20;
  return (
    <div>
      <p>Addition: {a + b}</p>
      <p>Multiplication: {a * b}</p>
    </div>
  );
}

Output:

Addition: 30
Multiplication: 200

3. Why Do We Embed Expressions in JSX?

Embedding expressions makes React applications dynamic and flexible. It allows the user interface to display information based on variables, calculations, application data and function results.

  • Dynamic content: Display changing names, messages and other data.
  • Calculations: Calculate totals, discounts, quantities and scores.
  • Data access: Display values stored inside objects and arrays.
  • Function results: Display formatted dates, names or other computed values.
  • Conditional rendering: Display different elements depending on a condition.
  • Dynamic attributes: Set image sources, alternative text and other properties using JavaScript variables.
  • Reusable components: Display different information in the same component using props and expressions.

4. Rule for Embedding Expressions in JSX

The main rule is to place a valid JavaScript expression inside curly braces when using it within JSX markup.

Syntax

{javascriptExpression}

Example

function App() {
  const course = "React JS";
  return <h1>Welcome to {course}</h1>;
}

Output: Welcome to React JS

Curly braces tell JSX to evaluate the JavaScript expression instead of treating its contents as ordinary text.

Expressions can be used in two common places:

  1. Between the opening and closing tags of a JSX element.
  2. Inside an attribute value immediately after the equals sign.

5. Embedding Variables in JSX

Variables store information that can be displayed inside JSX. Using variables avoids hardcoding the same information in multiple places and makes components easier to maintain.

Example

function App() {
  const studentName = "Priya";
  const courseName = "React JS";
  const duration = "3 Months";
  return (
    <div>
      <h1>Student Details</h1>
      <p>Name: {studentName}</p>
      <p>Course: {courseName}</p>
      <p>Duration: {duration}</p>
    </div>
  );
}
export default App;

Explanation:

  • studentName stores the student's name.
  • courseName stores the course name.
  • duration stores the course duration.
  • Curly braces insert each variable's value into the rendered content.

6. Embedding Arithmetic Expressions in JSX

Arithmetic expressions allow mathematical calculations to be performed directly inside JSX. This is useful for displaying prices, totals, marks, quantities and other numerical information.

Example

function App() {
  const price = 500;
  const quantity = 3;
  return (
    <div>
      <h1>Order Summary</h1>
      <p>Price: ₹{price}</p>
      <p>Quantity: {quantity}</p>
      <p>Total: ₹{price * quantity}</p>
    </div>
  );
}

Output:

Order Summary
Price: ₹500
Quantity: 3
Total: ₹1500

Common Arithmetic Operators

Operator Purpose Example Result
+ Addition {5 + 3} 8
- Subtraction {10 - 4} 6
* Multiplication {6 * 2} 12
/ Division {20 / 5} 4
% Remainder {10 % 3} 1
** Exponentiation {2 ** 3} 8

7. Embedding String Expressions in JSX

String expressions allow developers to combine text and variables. JavaScript concatenation and template literals are useful when displaying names, messages and descriptions.

Example Using Concatenation

function App() {
  const firstName = "Amit";
  const lastName = "Sharma";
  return (
    <h1>
      {"Hello, " + firstName + " " + lastName + "!"}
    </h1>
  );
}

Output: Hello, Amit Sharma!

Example Using a Template Literal

function App() {
  const name = "Amit";
  const course = "React JS";
  return (
    <p>{`${name} is learning ${course}.`}</p>
  );
}

Output: Amit is learning React JS.

Note: Template literals use backticks, while JSX uses curly braces to evaluate the complete template-literal expression.


8. Embedding Object Properties in JSX

JavaScript objects store related information in key-value pairs. JSX can display an individual property by using dot notation or bracket notation inside curly braces.

Example

function App() {
  const student = {
    name: "Neha",
    age: 21,
    course: "React JS"
  };
  return (
    <div>
      <h1>Student Profile</h1>
      <p>Name: {student.name}</p>
      <p>Age: {student.age}</p>
      <p>Course: {student.course}</p>
    </div>
  );
}

Explanation: Expressions such as {student.name} and {student.course} access individual properties and display their values.

Important: Do not try to render an entire ordinary JavaScript object directly as a child, such as {student}. React cannot display a plain object as text. Select a property such as {student.name} instead.


9. Embedding Function Calls in JSX

Functions can calculate or format information and return a value that JSX displays. This helps keep reusable logic separate from the markup.

Example

function getWelcomeMessage(name) {
  return "Welcome, " + name + "!";
}
function App() {
  return (
    <div>
      <h1>{getWelcomeMessage("Rahul")}</h1>
    </div>
  );
}
export default App;

Output: Welcome, Rahul!

Example Using a Formatting Function

function formatPrice(price) {
  return "₹" + price.toFixed(2);
}
function App() {
  const price = 249.5;
  return <p>Product Price: {formatPrice(price)}</p>;
}

Output: Product Price: ₹249.50

Functions used in JSX expressions should return values appropriate for rendering. Avoid placing side effects, such as changing application data, inside expressions that are evaluated during rendering.


10. Embedding Boolean Expressions in JSX

Boolean expressions produce either true or false. They are commonly used with comparison operators to decide which content should appear.

Example

function App() {
  const age = 20;
  return (
    <div>
      <p>Eligible for adult access: {age >= 18 ? "Yes" : "No"}</p>
    </div>
  );
}

Output: Eligible for adult access: Yes

Common Comparison Operators

Operator Meaning Example
=== Strictly equal {age === 18}
!== Not strictly equal {age !== 18}
> Greater than {age > 18}
< Less than {age < 18}
>= Greater than or equal to {age >= 18}
<= Less than or equal to {age <= 18}

A bare Boolean value such as {true} or {false} is not displayed as the words true or false in ordinary JSX text. Convert it to a string or use it in a conditional expression when you want visible output.


11. Conditional Expressions in JSX

Conditional expressions allow React to display different content depending on a condition. The most common techniques are the ternary operator and logical AND.

Using the Ternary Operator

function App() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome Back!</h1>
      ) : (
        <h1>Please Log In</h1>
      )}
    </div>
  );
}

Explanation: If isLoggedIn is true, React displays the welcome heading. Otherwise, it displays the login message.

Using Logical AND

function App() {
  const hasNotifications = true;
  return (
    <div>
      <h1>Dashboard</h1>
      {hasNotifications && <p>You have new notifications.</p>}
    </div>
  );
}

Explanation: The paragraph appears when hasNotifications is true.

Important: Be careful with numeric values in logical AND expressions. For example, {count && <p>Items available</p>} can display 0 if count is zero. A safer expression is {count > 0 && <p>Items available</p>}.


12. Embedding Expressions in JSX Attributes

JavaScript expressions can also be embedded in JSX attributes. This is useful when image URLs, alternative text, class names, titles or other attribute values depend on variables.

Example

function App() {
  const imageUrl = "/images/student.png";
  const imageDescription = "Student profile";
  const imageWidth = 200;
  return (
    <img
      src={imageUrl}
      alt={imageDescription}
      width={imageWidth}
    />
  );
}

In this example, the values of src, alt and width come from JavaScript variables.

String Attribute vs Expression Attribute

function App() {
  const course = "React JS";
  return (
    <div>
      <p title="Course Information">Fixed title</p>
      <p title={course}>Dynamic title</p>
    </div>
  );
}

Use quotation marks for a fixed string and curly braces for a JavaScript expression. Avoid combining both forms as title="{course}", because that passes the literal text rather than the variable's value.


13. Using Objects with JSX and Inline Styles

Sometimes a JavaScript object needs to be passed to a JSX attribute. Inline styles are a common example. The outer curly braces indicate a JavaScript expression, while the inner braces define the object.

Example

function App() {
  return (
    <h1
      style={{
        color: "blue",
        backgroundColor: "lightyellow",
        fontSize: "28px",
        textAlign: "center"
      }}
    >
      Welcome to React
    </h1>
  );
}

Explanation:

  • The outer braces switch from JSX markup to JavaScript.
  • The inner braces create the style object.
  • CSS properties generally use camelCase, such as backgroundColor.
  • Many CSS values are strings, while certain numeric properties can accept numbers.

Double curly braces are not a special JSX operator. They are simply a JavaScript object placed inside a JSX expression.


14. Embedding Array Expressions in JSX

Arrays can store multiple values. In React, the map() method is commonly used to transform array items into JSX elements.

Example

function App() {
  const courses = ["HTML", "CSS", "JavaScript", "React JS"];
  return (
    <div>
      <h1>Available Courses</h1>
      <ul>
        {courses.map((course) => (
          <li key={course}>{course}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Explanation: The map() expression creates one list item for each course. The key property gives React a stable identifier for each item in this example.

When rendering arrays of objects, use a unique identifier from each object as the key whenever possible.


15. What Cannot Be Used Directly as a JSX Expression?

Curly braces in JSX expect a valid JavaScript expression. JavaScript statements such as ordinary if and for statements cannot be inserted directly into JSX markup as though they were expressions.

Incorrect Example

function App() {
  const age = 20;
  return (
    <div>
      {if (age >= 18) {
        <p>Adult</p>
      }}
    </div>
  );
}

Problem: An ordinary if statement is not a valid expression in that JSX position.

Correct Example Using a Ternary Operator

function App() {
  const age = 20;
  return (
    <div>
      {age >= 18 ? <p>Adult</p> : <p>Minor</p>}
    </div>
  );
}

Alternative: Prepare a Variable Before Returning JSX

function App() {
  const age = 20;
  let message;
  if (age >= 18) {
    message = "Adult";
  } else {
    message = "Minor";
  }
  return <p>{message}</p>;
}

Best practice: Keep complicated logic outside the JSX return statement. Calculate a value before returning the markup, then display that value inside curly braces.


16. Difference Between JavaScript Expressions and Statements

Understanding expressions and statements is important when embedding JavaScript in JSX.

Feature Expression Statement
Meaning Produces a value. Performs an action or controls program execution.
Examples 2 + 3, user.name, getMessage() if, for, const name = "Amit"
Directly usable in JSX braces Yes, if it is a valid expression. Ordinary statements cannot be inserted directly as JSX expressions.
Typical use Display a value or select content. Declare variables or perform control flow before returning JSX.

Expression Example

<p>Result: {10 + 5}</p>

Statement Example

const result = 10 + 5;
return <p>Result: {result}</p>;

The second example calculates the result in JavaScript first and then embeds the resulting variable in JSX.


17. Common Mistakes When Embedding Expressions in JSX

Mistake Why It Is Incorrect Correct Approach
Writing a variable without braces The variable name may be treated as plain text. Use {name}.
Putting an expression in quotes The expression becomes a string. Use title={course}.
Rendering a whole object A plain object is not a valid React child. Render a property such as {student.name}.
Using an ordinary if statement inside JSX A statement is not valid in that expression position. Use a ternary expression or calculate the result beforehand.
Using logical AND with zero The numeric zero may appear in the UI. Use a condition such as count > 0.
Calling side-effect functions during rendering Rendering may occur more than once and cause unwanted effects. Use event handlers or appropriate React effects for side effects.
Using invalid attribute syntax JSX attributes follow JavaScript-oriented rules. Use the correct attribute and expression syntax.
Writing complicated expressions directly in JSX The component becomes difficult to read. Move the logic into a named variable or helper function.

18. Practical Example: Product Price Calculator

This practical example combines variables, arithmetic expressions, object properties, a function call and conditional rendering in one React component.

function ProductCard() {
  const product = {
    name: "Wireless Mouse",
    price: 800,
    quantity: 2,
    inStock: true
  };
  function formatPrice(amount) {
    return "₹" + amount.toFixed(2);
  }
  const total = product.price * product.quantity;
  return (
    <div className="product-card">
      <h1>{product.name}</h1>
      <p>Price: {formatPrice(product.price)}</p>
      <p>Quantity: {product.quantity}</p>
      <p>Total: {formatPrice(total)}</p>
      <p>
        {product.inStock ? "Available" : "Out of Stock"}
      </p>
    </div>
  );
}
export default ProductCard;

Expected Output

Wireless Mouse
Price: ₹800.00
Quantity: 2
Total: ₹1600.00
Available

Concepts Used

  • {product.name} accesses an object property.
  • {formatPrice(product.price)} embeds a function call.
  • {product.price * product.quantity} performs a calculation.
  • {product.inStock ? "Available" : "Out of Stock"} uses a conditional expression.
  • The JSX combines all the expressions into a single user interface.

19. Frequently Asked Interview Questions

Q1. What does embedding expressions in JSX mean?

It means inserting valid JavaScript expressions into JSX markup using curly braces so that their results can be displayed or passed as attribute values.

Q2. Why are curly braces used in JSX?

Curly braces allow JSX to evaluate JavaScript expressions, such as variables, calculations, function calls and object properties.

Q3. Can we perform calculations inside JSX?

Yes. Expressions such as {10 + 20} can calculate values that React displays in the user interface.

Q4. Can we call functions inside JSX?

Yes. A function call such as {getMessage()} can display the value returned by that function.

Q5. Can we display object properties in JSX?

Yes. You can display individual properties using expressions such as {student.name}. A plain object itself cannot normally be rendered directly as a child.

Q6. Can we use JavaScript statements directly inside JSX?

Ordinary statements such as if and for cannot be inserted directly into JSX expression positions. Use expressions such as ternaries and logical AND, or prepare values before returning JSX.

Q7. How do expressions work in JSX attributes?

Place a JavaScript expression inside curly braces immediately after the equals sign, such as src={imageUrl}.

Q8. What is the difference between a string and an expression in an attribute?

title="course" passes a fixed string, whereas title={course} passes the value of the JavaScript variable named course.

Q9. Can arrays be used in JSX?

Yes. Arrays of renderable values can be displayed, and map() is commonly used to turn arrays of data into JSX elements. List elements should have stable keys.

Q10. What is the purpose of conditional expressions?

Conditional expressions allow a component to choose which content to display based on a condition.


20. Practice Exercises

  1. Create a component that displays your name using a variable inside JSX.
  2. Display the sum, difference and product of two numbers.
  3. Create a student object and display its name, age and course.
  4. Write a function that returns a welcome message and display the result inside JSX.
  5. Display a product price after multiplying its price by its quantity.
  6. Use a ternary expression to display whether a student has passed or failed.
  7. Create a dynamic image using JavaScript variables for its source and alternative text.
  8. Render an array of programming courses using map() and unique keys.
  9. Apply inline styles using a JavaScript object.
  10. Show a notification only when a notification count is greater than zero.
  11. Correct an example that attempts to render a plain object directly in JSX.
  12. Refactor a complicated JSX expression into a variable defined before the return statement.

21. Quick Revision Checklist

  • Understand the meaning of a JavaScript expression.
  • Know how to use curly braces inside JSX.
  • Display variables and object properties in JSX.
  • Perform arithmetic and string operations inside expressions.
  • Call functions that return renderable values.
  • Use Boolean and conditional expressions correctly.
  • Pass dynamic values into JSX attributes.
  • Understand how objects and inline styles work with curly braces.
  • Render arrays using map() and stable keys.
  • Distinguish expressions from statements.
  • Avoid rendering plain objects directly as children.
  • Keep complex logic outside JSX to improve readability.

22. Conclusion

Embedding expressions in JSX is an important React skill that allows developers to combine JavaScript logic with user interface markup. By using curly braces, developers can display variables, calculate values, access object properties, call functions, create conditional content and set dynamic attributes. Mastering these techniques helps create interactive, reusable and maintainable React applications.

23. Learn React JS with JustAcademy

Explore the React JS Training Course to develop your skills in JSX, React components and modern frontend development.

JustAcademy React JS Training Course

Register for a demo session to learn more about the course and its training approach.

Register for React JS Course Demo

24. Official React Documentation

For further explanations and practical examples, refer to the official React documentation.

React Official Documentation: JavaScript in JSX with Curly Braces

React Official Documentation: Writing Markup with JSX

Previous Next
whatsapp