How JSX Works: Interview Explanation
⚛ ری‌اکت

How JSX Works: Interview Explanation

JSX is syntactic sugar — explain what Babel compiles it to and why React needs a single root.

BugCast Admin··۵ دقیقه مطالعه

JSX looks like HTML but is JavaScript. Understanding the compile output helps you debug keys, fragments, and the React.createElement mental model.

Common Interview Questions

Q: What does JSX compile to?

Answer: Babel transforms JSX into React.createElement calls (or the automatic JSX runtime imports jsx/jsxs from react/jsx-runtime).


// JSX
const el = <h1 className="title">Hello</h1>;
// Compiled (classic runtime)
const el = React.createElement("h1", { className: "title" }, "Hello");

Q: Why className instead of class?

Answer: class is a reserved word in JavaScript. JSX attributes map to DOM property names in camelCase (htmlFor, onClick).

Q: What are React Fragments?

Answer: Fragments group children without adding extra DOM nodes. Shorthand <>...</> compiles to React.Fragment.


return (
  <>
    <td>Cell 1</td>
    <td>Cell 2</td>
  </>
);

Q: Can you use JavaScript expressions in JSX?

Answer: Yes, inside {} — variables, function calls, ternaries, and map for lists. Statements (if/for) need to live outside JSX or use ternaries/IIFEs.

Key Points for Interviews

  • JSX is not a template language — it is JavaScript

  • One parent element unless using Fragment

  • Expressions in {} must evaluate to renderable values

  • Automatic runtime removes need to import React in scope (React 17+)

  • Keys go on elements inside lists, not Fragment shorthand

#jsx#babel#interview

مطالب مرتبط