R

React Handbook

Clean • Professional

JSX Expressions in React

1 minute

JSX Expressions

One of the key advantages of JSX in React is its ability to render dynamic content using JavaScript expressions. This allows developers to create interactive, data-driven user interfaces.

What Are JSX Expressions?

A JSX expression is any valid JavaScript code placed inside curly braces {} in JSX. React evaluates the expression and renders the result in the UI.

Example – Basic Expression:

const name = "John";
const element = <h1>Hello, {name}!</h1>;

Using Expressions for Calculations

You can perform math operations or functions directly inside JSX:

const a = 5;
const b = 10;
const element = <p>Sum: {a + b}</p>;

Calling Functions in JSX

JSX allows you to call JavaScript functions to render dynamic content:

function formatName(user) {
  return `${user.firstName} ${user.lastName}`;
}

const user = { firstName: "Jane", lastName: "Doe" };
const element = <h2>Hello, {formatName(user)}!</h2>;

Conditional Rendering with Expressions

You can use ternary operators or logical operators to conditionally render content:

Ternary Operator:

const isLoggedIn = true;
const greeting = <h1>{isLoggedIn ? "Welcome Back!" : "Please Log In"}</h1>;

Logical AND (&&) Operator:

const notifications = 3;
const element = <div>{notifications > 0 && <p>You have {notifications} new notifications</p>}</div>;

Rendering Arrays and Lists

You can render dynamic lists using map() inside JSX:

const fruits = ["Apple", "Banana", "Orange"];
const fruitList = (
  <ul>
    {fruits.map((fruit, index) => (
      <li key={index}>{fruit}</li>
    ))}
  </ul>
);

Expressions Are Not Limited to Text

JSX expressions can render:

  • Numbers and calculations
  • Strings and variables
  • Functions
  • Conditional content
  • Lists and arrays
  • Components

Example – Component Rendering:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

const element = <Welcome name="John" />;

 

Article 0 of 0