What is JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your React components. It makes creating and visualizing UI components more intuitive by blending markup and logic.

Key Characteristics of JSX

1. HTML-Like Syntax in JavaScript

  • Write familiar HTML tags directly in JavaScript.

  • Example:

    jsx

    const element = <h1>Hello, JSX!</h1>;

  • Not a string or HTML—it gets compiled to React.createElement() calls.

2. Embed JavaScript Expressions

  • Use curly braces {} to embed dynamic values or logic.

  • Example:

    jsx
    const name = "Alice";
    const greeting = <p>Hello, {name}!</p>; // Renders: <p>Hello, Alice!</p>

3. Self-Closing Tags

  • JSX follows XML rules, so tags like <img> must be closed:

    jsx
    <img src="logo.png" alt="Logo" />  // ✅ Correct
    <img src="logo.png" alt="Logo">    // ❌ Error in JSX

4. Class vs. className

  • Since class is a reserved word in JavaScript, JSX uses className:

    jsx
    <div className="container">Content</div>

5. Must Return a Single Root Element

  • Wrap adjacent elements in a parent (e.g., <div><> Fragment):

    jsx
    return (
      <div>
        <h1>Title</h1>
        <p>Description</p>
      </div>
    );


How JSX Works Under the Hood

Babel (a JavaScript compiler) transforms JSX into plain JavaScript:

JSX Code:

jsx
const element = <h1 className="title">Hello</h1>;

Compiled JavaScript:

js
const element = React.createElement("h1", { className: "title" }, "Hello");


Why Use JSX?

✅ Readability: Easier to visualize UI structure.
✅ Safety: Prevents injection attacks (XSS) by escaping embedded values.
✅ Performance: Optimized by React’s Virtual DOM.


Common JSX Patterns

  1. Conditional Rendering

    jsx
    {isLoggedIn ? <button>Logout</button> : <button>Login</button>}
  2. Loops

    jsx
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  3. Inline Styles

    jsx
    <div style={{ color: "red", fontSize: "20px" }}>Warning!</div>


JSX vs. HTML Differences

FeatureJSXHTML
AttributesclassNamehtmlForclassfor
StylesObject (e.g., {{color: 'red'}})String (e.g., style="color:red")
Comments{/* Comment */}<!-- Comment -->


Example: Functional Component with JSX

jsx
function Greeting({ name }) {
  return (
    <div className="greeting">
      <h1>Hello, {name}!</h1>
      <p>Today is {new Date().toLocaleDateString()}</p>
    </div>
  );
}


Key Takeaways

  • JSX is not HTML—it’s syntactic sugar for React.createElement().

  • Combines JavaScript + Markup for expressive UI code.

  • Required for most React projects (though technically optional).

To Top