How to Implement JSX in React

JSX, or JavaScript XML, is a syntax extension for JavaScript widely used in React to describe what the user interface should look like. This article provides a straightforward guide on how to implement JSX in your React applications, covering its basic syntax, the essential rules for writing it, and how React processes it under the hood.

Writing Your First JSX Element

In React, JSX allows you to write HTML-like structures directly inside your JavaScript files. To implement JSX, you simply assign the HTML-like markup to a variable or return it from a React component.

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

When creating a functional component, you return the JSX block to render it to the screen:

function Welcome() {
  return <h1>Welcome to my React app!</h1>;
}

Embedding JavaScript Expressions

One of the main benefits of JSX is the ability to embed JavaScript expressions directly within the markup. You can do this by wrapping the JavaScript code in curly braces {}.

function UserProfile() {
  const name = "Alice";
  return <h1>Hello, {name}!</h1>;
}

You can put any valid JavaScript expression inside the curly braces, such as variable names, mathematical operations, function calls, or ternary operators for conditional rendering.

Key Rules for Implementing JSX

To ensure your JSX compiles correctly, you must follow three fundamental rules:

  1. Return a Single Root Element: JSX expressions must have only one outermost parent element. If you need to return multiple adjacent elements, wrap them in a single parent container or use a React Fragment (<>...</>) to avoid adding extra nodes to the DOM.

    // Correct implementation using a Fragment
    return (
      <>
        <h1>Title</h1>
        <p>Paragraph text.</p>
      </>
    );
  2. Close All Tags: Unlike standard HTML, every tag in JSX must be explicitly closed. Self-closing tags, such as <img>, <br>, and <input>, must end with a forward slash.

    <img src="logo.png" alt="Logo" />
  3. Use camelCase for Attributes: Because JSX compiles to JavaScript, it uses JavaScript’s camelCase naming convention instead of standard HTML attribute names. For example, use className instead of class, and onClick instead of onclick.

    <button className="btn-primary" onClick={handleClick}>Click Me</button>

How JSX Works Under the Hood

Web browsers cannot read JSX directly. During the build process, a compiler like Babel translates your JSX code into standard JavaScript function calls.

For example, this JSX code:

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

Is compiled into:

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

Modern React toolchains handle this translation automatically, allowing you to write clean, declarative UI layouts without worrying about manual browser compatibility.