Understanding JSX
Overview
JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like markup directly inside your JavaScript files. While it looks exactly like HTML, under the hood it is compiled into plain JavaScript functions (like React.createElement). Because it's ultimately JavaScript, it has a few strict rules you must follow compared to standard HTML.
Syntax
A component can only return one single parent element. If you don't want to add unnecessary <div> tags to the DOM, use the Fragment syntax `<> </>`.
// ❌ BAD: Returning two sibling elements
function BadComponent() {
return (
<h1>Hello</h1>
<p>World</p>
);
}
// ✅ GOOD: Wrap in a Fragment (empty tags)
function GoodComponent() {
return (
<>
<h1>Hello</h1>
<p>World</p>
</>
);
}In JSX, tags without a closing tag (like img, input, br) MUST be self-closed with a trailing slash. Furthermore, because 'class' and 'for' are reserved words in JS, you must use 'className' and 'htmlFor'.
// ❌ BAD: Unclosed tag and HTML-style attributes
<img src="pic.jpg" class="profile" onclick="doSomething()">
// ✅ GOOD: Self-closing tag and camelCase attributes
<img src="pic.jpg" className="profile" onClick={doSomething} />Common Pitfalls
- Using 'class' instead of 'className'. It might work and render, but it will throw a massive warning in your browser console.
- Forgetting to wrap your return statement in parentheses when writing multi-line JSX.
Interview Tips
- Explain that JSX is syntactic sugar. The browser cannot understand JSX. Tools like Babel or SWC compile it into standard JavaScript before it reaches the browser.
Real-World Example
Writing complex SVG icons as React components requires strict adherence to JSX camelCase rules.
function CheckIcon() {
return (
// 'stroke-width' becomes 'strokeWidth', 'stroke-linecap' becomes 'strokeLinecap'
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
<path d="M20 6L9 17l-5-5" />
</svg>
);
}