JSX Variables

Variables are one of the simplest and most important ways to make a React interface dynamic.

In JSX, you can create JavaScript variables inside a component and then use those variables to display text, numbers, attributes, styles, and other values in the UI.

For example:

function App() {
  const name = "John";

  return <h1>Hello, {name}!</h1>;
}

The variable name contains "John", and {name} tells JSX to evaluate the variable and display its value.

This basic pattern appears throughout React applications.

Creating Variables Inside a Component

Variables are commonly declared inside the component body.

function App() {
  const name = "John";
  const age = 25;

  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
    </div>
  );
}

The variables are created before the return statement and then used inside the JSX.

A component can contain many variables:

function App() {
  const firstName = "John";
  const lastName = "Smith";
  const age = 25;
  const profession = "Developer";

  return (
    <div>
      <h1>{firstName} {lastName}</h1>
      <p>Age: {age}</p>
      <p>Profession: {profession}</p>
    </div>
  );
}

Using Variables Inside JSX

To use a JavaScript variable in JSX, place its name inside curly braces.

const message = "Welcome to React";

return <h1>{message}</h1>;

Without curly braces:

return <h1>message</h1>;

React treats message as ordinary text.

With curly braces:

return <h1>{message}</h1>;

React evaluates the variable and displays its value.

This distinction is important:

"message"
   ↓
Literal text

{message}
   ↓
JavaScript variable

Variables Can Store Strings

Strings are frequently used to provide text content.

function App() {
  const title = "Learn React";
  const description = "Build modern web applications.";

  return (
    <div>
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  );
}

This makes your JSX easier to modify because the displayed text is stored separately from the UI structure.

Variables Can Store Numbers

Variables can also contain numbers.

function App() {
  const price = 2500;
  const quantity = 3;

  return (
    <div>
      <p>Price: ₹{price}</p>
      <p>Quantity: {quantity}</p>
    </div>
  );
}

You can also perform calculations:

const total = price * quantity;

return <p>Total: ₹{total}</p>;

This is often cleaner than putting a long calculation directly inside JSX.

Variables Can Store Boolean Values

Boolean variables contain either true or false.

function App() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome back!</p>
      ) : (
        <p>Please log in.</p>
      )}
    </div>
  );
}

Boolean variables are commonly used for:

  • Login status
  • Loading states
  • Visibility
  • Permissions
  • Availability
  • Selection states
  • Feature settings

Variables Can Store Objects

A variable can store an object containing multiple related values.

function App() {
  const user = {
    name: "John",
    age: 25,
    role: "Developer"
  };

  return (
    <div>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}

Instead of creating separate variables:

const name = "John";
const age = 25;
const role = "Developer";

you can group related information:

const user = {
  name: "John",
  age: 25,
  role: "Developer"
};

This becomes particularly useful when handling structured application data.

Variables Can Store Arrays

Arrays are useful for storing collections of data.

function App() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

The variable fruits contains multiple values.

The .map() method transforms each item into JSX.

You will use this pattern frequently when displaying lists of users, products, posts, messages, and other data.

Variables Can Store JSX

A variable can also contain JSX.

function App() {
  const heading = <h1>Welcome to React</h1>;

  return (
    <div>
      {heading}
    </div>
  );
}

Here, heading stores a JSX element.

You can then use it inside another JSX structure:

{heading}

This can be useful in certain situations, although you should avoid creating unnecessary JSX variables when a component or simpler expression would make the code clearer.

Variables Can Store Calculated Values

You can calculate values before returning JSX.

function App() {
  const price = 1000;
  const quantity = 4;
  const discount = 100;

  const subtotal = price * quantity;
  const total = subtotal - discount;

  return (
    <div>
      <p>Subtotal: ₹{subtotal}</p>
      <p>Discount: ₹{discount}</p>
      <p>Total: ₹{total}</p>
    </div>
  );
}

This is generally easier to read than putting all the calculations directly inside JSX.

Variables Can Store Function Results

A variable can store the result returned by a function.

function formatName(name) {
  return name.toUpperCase();
}

function App() {
  const name = "John";
  const formattedName = formatName(name);

  return <h1>{formattedName}</h1>;
}

The process is:

name
 ↓
formatName(name)
 ↓
formattedName
 ↓
JSX

This approach is useful when data needs to be processed before it is displayed.

Variables Can Be Used in Attributes

Variables can also provide values for JSX attributes.

function App() {
  const imageUrl = "/images/profile.jpg";
  const imageAlt = "User profile";

  return (
    <img
      src={imageUrl}
      alt={imageAlt}
    />
  );
}

The variables are connected to the attributes using curly braces.

You can do the same with many other attributes:

const buttonText = "Submit";
const isDisabled = false;

return (
  <button disabled={isDisabled}>
    {buttonText}
  </button>
);

Variables Can Control CSS Classes

A variable can determine which CSS class an element receives.

function App() {
  const isActive = true;

  const buttonClass = isActive
    ? "button active"
    : "button";

  return (
    <button className={buttonClass}>
      Profile
    </button>
  );
}

This is useful when the appearance of an element depends on application data.

A shorter approach can be used for simple conditions:

<button className={isActive ? "active" : "inactive"}>
  Profile
</button>

Variables Can Control Inline Styles

Variables can also be used with inline styles.

function App() {
  const textColor = "blue";
  const fontSize = 24;

  return (
    <h1
      style={{
        color: textColor,
        fontSize: `${fontSize}px`
      }}
    >
      Hello React
    </h1>
  );
}

The variables provide dynamic style values.

Variables and Conditional Rendering

Variables are often used to decide which JSX should be rendered.

function App() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn && <p>You are logged in.</p>}
    </div>
  );
}

You can also use a ternary expression:

const isLoggedIn = true;

return (
  <h1>
    {isLoggedIn ? "Dashboard" : "Login"}
  </h1>
);

For more complicated conditions, create a variable first.

const age = 22;
const hasPermission = true;

const canAccess = age >= 18 && hasPermission;

return (
  <p>
    {canAccess ? "Access granted" : "Access denied"}
  </p>
);

This makes the JSX easier to understand.

Variables and Lists

Variables make list rendering easier to organize.

function App() {
  const products = [
    { id: 1, name: "Laptop" },
    { id: 2, name: "Phone" },
    { id: 3, name: "Tablet" }
  ];

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name}
        </li>
      ))}
    </ul>
  );
}

The products variable stores the data, while .map() converts each object into JSX.

This separation between data and UI structure is a common React pattern.

Variables Can Be Destructured

JavaScript destructuring can make object values easier to use.

Instead of:

const user = {
  name: "John",
  age: 25
};

return (
  <div>
    <h2>{user.name}</h2>
    <p>{user.age}</p>
  </div>
);

you can write:

const user = {
  name: "John",
  age: 25
};

const { name, age } = user;

return (
  <div>
    <h2>{name}</h2>
    <p>{age}</p>
  </div>
);

Both approaches are valid.

Destructuring becomes especially useful when working with component props.

Variables Can Be Used in Event Handlers

Variables can also be used when handling events.

function App() {
  const message = "Button clicked!";

  function handleClick() {
    console.log(message);
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

The event handler can access variables from the component’s scope.

You can also pass variables to functions:

function showMessage(message) {
  console.log(message);
}

function App() {
  const message = "Hello React";

  return (
    <button onClick={() => showMessage(message)}>
      Click Me
    </button>
  );
}

Variable Scope Inside Components

Variables declared inside a component are local to that component.

function App() {
  const name = "John";

  return <h1>{name}</h1>;
}

The name variable belongs to the App function.

Another component cannot directly access it:

function App() {
  const name = "John";

  return <Profile />;
}

function Profile() {
  // name is not directly available here
  return <h2>Profile</h2>;
}

If another component needs the value, you normally pass it through props.

function App() {
  const name = "John";

  return <Profile name={name} />;
}

function Profile({ name }) {
  return <h2>{name}</h2>;
}

This is an important concept because React applications are usually divided into many components.

Regular Variables vs State Variables

A regular variable inside a component is not the same as React state.

For example:

function App() {
  let count = 0;

  function handleClick() {
    count++;
    console.log(count);
  }

  return (
    <button onClick={handleClick}>
      {count}
    </button>
  );
}

Changing count does not automatically tell React to render the component again.

For values that need to change and cause the UI to update, React provides state.

For example:

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

Here, count is state rather than an ordinary variable.

When setCount() updates the state, React can render the component again with the new value.

State is covered in much more detail later in the React learning process.

Variables Are Recreated During Rendering

A component function can run multiple times during its lifetime.

Consider:

function App() {
  const message = "Hello React";

  return <h1>{message}</h1>;
}

Whenever React renders the component, the component function executes and the local variable is created again.

This is one reason regular variables should not be used as a replacement for React state when you need a value to persist between renders and update the UI.

Variables Should Usually Be Declared Before return

A common and readable structure is:

function App() {
  const name = "John";
  const age = 25;
  const isStudent = true;

  return (
    <div>
      <h1>{name}</h1>
      <p>{age}</p>
      <p>{isStudent ? "Student" : "Not a student"}</p>
    </div>
  );
}

This creates a clear separation:

Component
   ↓
JavaScript data and logic
   ↓
return
   ↓
JSX UI

This structure becomes increasingly useful as components become more complex.

Avoid Unnecessary Variables

Variables are useful, but creating a variable for every tiny expression can make code unnecessarily long.

For example:

const name = "John";

return <h1>{name}</h1>;

is perfectly reasonable.

But this:

const message = "Hello";
const heading = <h1>{message}</h1>;

return <div>{heading}</div>;

may be unnecessary if the JSX is only used once.

You could simply write:

const message = "Hello";

return (
  <div>
    <h1>{message}</h1>
  </div>
);

The goal is not to create as many variables as possible. The goal is to make the code clear and maintainable.

A Complete JSX Variables Example

Here is a practical example combining several types of variables:

function ProductCard() {
  const product = {
    name: "Wireless Headphones",
    price: 2500,
    quantity: 2,
    inStock: true
  };

  const subtotal = product.price * product.quantity;
  const discount = subtotal * 0.1;
  const total = subtotal - discount;

  const stockMessage = product.inStock
    ? "In Stock"
    : "Out of Stock";

  return (
    <div className="product-card">
      <h2>{product.name}</h2>

      <p>Price: ₹{product.price}</p>

      <p>Quantity: {product.quantity}</p>

      <p>Subtotal: ₹{subtotal}</p>

      <p>Discount: ₹{discount}</p>

      <p>Total: ₹{total}</p>

      <p>{stockMessage}</p>

      <button disabled={!product.inStock}>
        Buy Now
      </button>
    </div>
  );
}

This example demonstrates how JavaScript variables can keep JSX organized.

The data is stored in product, calculations are stored in separate variables, and the final values are inserted into the JSX.

Common Mistakes

Forgetting Curly Braces

Incorrect:

<h1>name</h1>

Correct:

<h1>{name}</h1>

Putting a Variable Inside Quotes

Incorrect:

<img src="imageUrl" />

Correct:

<img src={imageUrl} />

Using a Regular Variable for UI State

Incorrect approach:

let count = 0;

function handleClick() {
  count++;
}

Changing the variable does not automatically update the displayed UI.

Use React state when the value needs to change and trigger a render:

const [count, setCount] = useState(0);

Accessing a Missing Object Property

If an object might not contain a property, accessing deeply nested data without checking can cause errors.

For example:

const user = {};

return <h2>{user.profile.name}</h2>;

A safer approach when the data may be missing is:

return <h2>{user.profile?.name ?? "Guest"}</h2>;

Creating Too Many Variables

Do not create variables simply to avoid writing a simple expression once.

Keep simple expressions simple and use variables when they improve readability, reuse, or organization.

Where to Place an Image

Image Placement: After “Using Variables Inside JSX”

Create a 16:9 React infographic showing how a JavaScript variable connects to JSX.

Visual:

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

Use a modern developer-themed design with React branding and a clear visual connection between the variable, JSX expression, and rendered UI.

Caption:
JavaScript variables provide dynamic values that can be displayed directly inside JSX.

Alt text:
JSX variables infographic showing a JavaScript variable being inserted into JSX and rendered as React UI.

Practice Exercise

Create a StudentCard component using the following variables:

const name = "Alex";
const course = "React Development";
const age = 22;
const score = 85;
const isOnline = true;

Use the variables to display:

  • Student name
  • Course
  • Age
  • Score
  • Online or offline status
  • Pass or fail status

Then create a calculated variable:

const passed = score >= 40;

Use it in your JSX:

{passed ? "Passed" : "Failed"}

Finally, create an object instead of separate variables and try displaying the same information using object properties.

Key Takeaways

JSX variables provide a simple way to connect JavaScript data with your React UI.

Remember:

  • Variables are normally declared inside the component.
  • Use {variable} to display a variable in JSX.
  • Variables can store strings, numbers, booleans, objects, arrays, and more.
  • Variables can provide dynamic JSX attributes.
  • Variables can control conditional rendering.
  • Variables can store calculated values.
  • Variables can store function results.
  • Arrays can be rendered using .map().
  • Destructuring can make object values easier to access.
  • Regular variables do not replace React state.
  • Use state when changing a value needs to update the UI.
  • Keep variables that improve readability and avoid unnecessary ones.

The basic pattern to remember is:

JavaScript Variable
       ↓
    {variable}
       ↓
       JSX
       ↓
    React UI

Once JSX variables are comfortable, the next step is understanding functions in JSX, including calling functions, passing arguments, formatting values, and handling events.