← Back to React, page 1

react-0003 · Easy fresher

What is JSX and how does it work under the hood?

JSX is a syntax extension that lets you write markup-like code inside JavaScript. It is not understood by browsers. A compiler such as Babel, SWC or esbuild turns each JSX tag into a call to the JSX runtime function, which returns a plain object describing the element. React reads those objects to build the UI.

Full answer

JSX looks like HTML but is JavaScript. A line such as <h1 className="title">Hello, {name}</h1> is turned by the build tool into a function call. With the automatic runtime (available since React 17 and the default in current tools), the compiler imports jsx and jsxs from react/jsx-runtime, so you no longer import React in every file.

Here is the kind of call a compiler produces for <h1 className="title">Hello, {name}</h1>, run by hand:

js
import { jsxs } from 'react/jsx-runtime';

const name = 'Asha';
const element = jsxs('h1', { className: 'title', children: ['Hello, ', name] });

console.log(element.type, element.props);
// h1 { className: 'title', children: [ 'Hello, ', 'Asha' ] }

Each call returns an element: a small object with a type (a tag name or a component), props and a key. It is only a description. React later compares these descriptions to decide what to change in the DOM.

The rules follow from this. An expression goes inside curly braces, but a statement such as if or for does not, so use a ternary, && or map. A component returns one root, which can be a fragment (<>...</>). HTML attributes use camelCase and class becomes className because class is a reserved word in JavaScript. Every tag must be closed, including <img />. A component name must start with a capital letter, otherwise it is treated as an HTML tag.

JSX also escapes values placed inside braces. A string such as <script> is rendered as text, which blocks most cross-site scripting. The risky exception is dangerouslySetInnerHTML.

JSX is optional. You could call jsx or createElement by hand, but nobody does it for real UI.

jsx
const students = [
  { id: 1, name: 'Asha', marks: 82 },
  { id: 2, name: 'Ravi', marks: 47 },
];

export default function Results() {
  const passMark = 50;
  return (
    <section className="results">
      <h2>Class results</h2>
      <ul>
        {students.map((s) => (
          <li key={s.id} style={{ color: s.marks >= passMark ? 'green' : 'red' }}>
            {s.name}: {s.marks} {s.marks >= passMark ? 'Pass' : 'Fail'}
          </li>
        ))}
      </ul>
      <label htmlFor="note">Note</label>
      <input id="note" defaultValue="Check re-evaluation" />
    </section>
  );
}

The example uses an expression for the pass mark check, map for the list, a style object, className and htmlFor. No React import is needed. Rendered result: <section class="results"><h2>Class results</h2><ul><li style="color: green;">Asha: 82 Pass</li><li style="color: red;">Ravi: 47 Fail</li></ul><label for="note">Note</label><input id="note" value="Check re-evaluation"></section>

Key points

  • JSX is syntax sugar compiled to jsx() calls. Browsers never see it.
  • The automatic runtime means you do not need to import React just to use JSX.
  • A JSX expression produces a plain object describing UI, not a DOM node.
  • Only expressions go inside braces. Use ternary, && or map instead of if and for.
  • Values inside braces are escaped, which protects against most injection issues.

Common mistakes

  • Writing class or for instead of className and htmlFor.
  • Returning two sibling elements without a wrapper or fragment.
  • Putting an if statement or a for loop directly inside braces.
  • Using a lowercase component name such as `<card />`, which React treats as an HTML tag.
  • Passing inline style as a string instead of an object.

Follow-ups

  • What is the difference between jsx() and React.createElement()?
  • Why can JSX output not be mutated after it is created?
  • How does React avoid cross-site scripting when you render user text in JSX?

Tips

  • Say what JSX compiles to. Many candidates only say "HTML in JavaScript".
  • Mention the automatic runtime to show you know why modern files have no React import.
  • Keep the answer free of a long list of rules. Pick two or three that cause real bugs, such as className and single root.