What is JSX?
JSX (JavaScript XML) is an extension of JavaScript syntax that lets you write HTML-like code directly inside JS. It is used in React to declaratively describe what the interface (UI) should look like.
JSX example:
function App() {
return <h1>Hello, world!</h1>;
}This code looks like HTML, but it actually compiles into ordinary JavaScript calls:
React.createElement("h1", null, "Hello, world!");Why JSX is needed
Without JSX you would write React components like this:
return React.createElement("div", null,
React.createElement("h1", null, "Title"),
React.createElement("p", null, "Paragraph text")
);With JSX it is much simpler and clearer:
return (
<div>
<h1>Title</h1>
<p>Paragraph text</p>
</div>
);Key features of JSX:
- Embedding JavaScript in markup
Inside curly braces
{}you can write JS expressions:
const name = "Tim";
return <h1>Hello, {name}!</h1>;- JSX is not a template, it is JS syntax Everything you write ultimately turns into JavaScript functions (via Babel or SWC).
- One root element A JSX block must return only one parent element:
return (
<div>
<h1>Title</h1>
<p>Description</p>
</div>
);
)
// You can't return two elements at the same level without a wrapperIf you don't want to add an extra <div>, you can use a fragment:
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);- Attributes - like in HTML, but in JS style:
-
class->className -
for->htmlFor -
values - in
{}:javascript<img src={imageUrl} alt="Photo" /> <button disabled={isDisabled}>Button</button>
- JSX can contain components
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
function App() {
return <Greeting name="Tim" />;
}Why JSX is convenient
The code reads like markup, but keeps the power of JavaScript You can use variables, functions and conditions directly in the UI It improves clarity and development speed
Example with a condition and a list
function TodoList({ todos }) {
return (
<ul>
{todos.length === 0 ? (
<p>No tasks</p>
) : (
todos.map(todo => <li key={todo.id}>{todo.text}</li>)
)}
</ul>
);
}JSX lets you embed logic directly into the interface structure - this is its superpower.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.