Knowledge Base (JSX)

· 1 min · 344 words

Overview

JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like markup directly within JavaScript or TypeScript code. Popularized by React, JSX serves as syntactic sugar for underlying JavaScript function calls, providing a declarative and intuitive way to construct user interfaces.


Technical Details & Compilation

Browsers cannot natively parse JSX syntax. During the build process, compilers (such as Babel, TypeScript, Vite, or SWC) transpile JSX elements into standard JavaScript function calls.

The Transformation Process

When the compiler encounters a JSX tag, it converts it into a call to a createElement function (or the modern JSX transform introduced in React 17):

  • Source JSX:
    const element = <h1 className="header">Hello, World!</h1>;
  • Compiled JavaScript (Classic Transform):
    const element = React.createElement(
      'h1',
      { className: 'header' },
      'Hello, World!'
    );

Core Characteristics & Features

1. Embedded JavaScript Expressions

Any valid JavaScript expression can be injected directly into JSX markup by enclosing it in curly braces {}. This includes variables, function calls, conditional ternary operators, and array methods.

2. Attribute Expressions and CamelCase Naming

JSX attributes use camelCase naming conventions instead of standard HTML kebab-case (e.g., className instead of class, and htmlFor instead of for). JavaScript expressions can also be passed directly into attributes.

3. Strict XML/HTML Rules

Unlike loose HTML parsing in browsers, JSX enforces strict XML rules:

  • Every opening tag must have a corresponding closing tag or be explicitly self-closing (e.g., <br />, <img src="..." />).
  • Components and elements must return a single root node. Multiple adjacent elements must be wrapped in a parent container or an invisible fragment (<> ... </>).

Code Examples

Example 1: Basic JSX Component

import React from 'react';

function UserProfile({ user }) {
  return (
    <div className="profile-card">
      <h2>{user.name}</h2>
      <p>Role: {user.role}</p>
      {user.isActive ? <span className="badge active">Online</span> : <span className="badge">Offline</span>}
    </div>
  );
}

Example 2: Dynamic Rendering with Arrays (Lists)

function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id} className={task.completed ? 'completed' : 'pending'}>
          {task.title}
        </li>
      ))}
    </ul>
  );
}

Comparison: With vs. Without JSX

FeatureWithout JSX (Pure JS)With JSX
SyntaxVerbose function nesting (React.createElement)Declarative, HTML-like markup
ReadabilityDifficult to visualize deep DOM treesHighly readable structure matching visual output
ToolingStandard JS syntax highlightersAdvanced IDE support, linting, and autocomplete