0
0
ReactHow-ToBeginner · 3 min read

How to Use JavaScript in JSX: Simple React Guide

In JSX, you can use JavaScript by placing expressions inside { } curly braces. This lets you embed variables, functions, or any JavaScript code directly within your HTML-like JSX markup.
📐

Syntax

JSX lets you write JavaScript expressions inside curly braces { }. Anything inside these braces is treated as JavaScript and evaluated. You can use variables, function calls, or any valid JavaScript expression.

  • Curly braces: Wrap JavaScript code inside { }.
  • Expressions only: You cannot put statements like if or for directly inside, only expressions.
  • Return values: The expression's result is inserted into the JSX output.
jsx
const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;
Output
Hello, Alice!
💻

Example

This example shows how to use JavaScript variables, expressions, and functions inside JSX to create a dynamic greeting message.

jsx
import React from 'react';

function Greeting() {
  const user = { firstName: 'John', lastName: 'Doe' };
  function formatName(user) {
    return `${user.firstName} ${user.lastName}`;
  }

  return (
    <div>
      <h1>Hello, {formatName(user)}!</h1>
      <p>2 + 2 = {2 + 2}</p>
      <p>{user.firstName.length > 3 ? 'Long name' : 'Short name'}</p>
    </div>
  );
}

export default Greeting;
Output
Hello, John Doe! 2 + 2 = 4 Long name
⚠️

Common Pitfalls

Common mistakes when using JavaScript in JSX include:

  • Trying to use statements like if or for directly inside { }. Use ternary operators or move logic outside JSX.
  • Forgetting to wrap JavaScript expressions in curly braces.
  • Returning undefined or null unintentionally, which can cause blank output.
jsx
/* Wrong: Using if statement inside JSX */
const element = <div>{true && 'Yes'}</div>;

/* Right: Use ternary operator */
const element = <div>{true ? 'Yes' : 'No'}</div>;
📊

Quick Reference

Remember these tips when using JavaScript in JSX:

  • Use { } to embed JavaScript expressions.
  • Only expressions are allowed inside { }, not statements.
  • Use ternary operators for conditional rendering.
  • Keep complex logic outside JSX for clarity.

Key Takeaways

Use curly braces { } to embed JavaScript expressions inside JSX.
Only JavaScript expressions (not statements) can go inside JSX curly braces.
Use ternary operators or functions for conditional logic inside JSX.
Keep complex JavaScript logic outside JSX for cleaner code.
Always test JSX output to ensure JavaScript expressions render as expected.