0
0
Reactframework~5 mins

Embedding expressions in JSX in React

Choose your learning style9 modes available
Introduction

Embedding expressions in JSX lets you show dynamic values inside your React components. It helps make your UI change based on data or user actions.

Showing a user's name inside a greeting message.
Displaying the current date or time that updates.
Calculating and showing a total price in a shopping cart.
Conditionally showing text or elements based on a value.
Syntax
React
const element = <tag>{expression}</tag>;
Use curly braces {} to embed any JavaScript expression inside JSX.
Expressions can be variables, math, function calls, or ternary conditions.
Examples
Shows a variable inside JSX to greet the user by name.
React
const name = 'Alex';
const greeting = <h1>Hello, {name}!</h1>;
Embeds a math expression result inside a paragraph.
React
const sum = 5 + 3;
const result = <p>5 + 3 = {sum}</p>;
Uses a ternary expression to show different text based on a condition.
React
const isLoggedIn = true;
const message = <p>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</p>;
Sample Program

This React component shows a greeting that changes based on the time of day. It uses expressions inside JSX to embed variables and a condition.

React
import React from 'react';

function Greeting() {
  const userName = 'Jamie';
  const hour = new Date().getHours();
  const greetingMessage = hour < 12 ? 'Good morning' : 'Good afternoon';

  return (
    <main>
      <h1>{greetingMessage}, {userName}!</h1>
      <p>Current hour: {hour}</p>
    </main>
  );
}

export default Greeting;
OutputSuccess
Important Notes

Only JavaScript expressions (not statements) can go inside curly braces.

Expressions inside JSX are automatically converted to strings or elements.

Use parentheses to wrap complex expressions for better readability.

Summary

Use curly braces {} to embed JavaScript expressions inside JSX.

Expressions can be variables, calculations, or conditional logic.

This makes your React UI dynamic and responsive to data changes.