What is JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your React components. It makes creating and visualizing UI components more intuitive by blending markup and logic.
Key Characteristics of JSX
1. HTML-Like Syntax in JavaScript
Write familiar HTML tags directly in JavaScript.
Example:
jsxconst element = <h1>Hello, JSX!</h1>;
Not a string or HTML—it gets compiled to
React.createElement()
calls.
2. Embed JavaScript Expressions
Use curly braces
{}
to embed dynamic values or logic.Example:
const name = "Alice"; const greeting = <p>Hello, {name}!</p>; // Renders: <p>Hello, Alice!</p>
3. Self-Closing Tags
JSX follows XML rules, so tags like
<img>
must be closed:<img src="logo.png" alt="Logo" /> // ✅ Correct <img src="logo.png" alt="Logo"> // ❌ Error in JSX
4. Class vs. className
Since
class
is a reserved word in JavaScript, JSX usesclassName
:<div className="container">Content</div>
5. Must Return a Single Root Element
Wrap adjacent elements in a parent (e.g.,
<div>
,<>
Fragment):return ( <div> <h1>Title</h1> <p>Description</p> </div> );
How JSX Works Under the Hood
Babel (a JavaScript compiler) transforms JSX into plain JavaScript:
JSX Code:
const element = <h1 className="title">Hello</h1>;
Compiled JavaScript:
const element = React.createElement("h1", { className: "title" }, "Hello");
Why Use JSX?
✅ Readability: Easier to visualize UI structure.
✅ Safety: Prevents injection attacks (XSS) by escaping embedded values.
✅ Performance: Optimized by React’s Virtual DOM.
Common JSX Patterns
Conditional Rendering
{isLoggedIn ? <button>Logout</button> : <button>Login</button>}
Loops
<ul> {items.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul>
Inline Styles
<div style={{ color: "red", fontSize: "20px" }}>Warning!</div>
JSX vs. HTML Differences
Feature | JSX | HTML |
---|---|---|
Attributes | className , htmlFor | class , for |
Styles | Object (e.g., {{color: 'red'}} ) | String (e.g., style="color:red" ) |
Comments | {/* Comment */} | <!-- Comment --> |
Example: Functional Component with JSX
function Greeting({ name }) { return ( <div className="greeting"> <h1>Hello, {name}!</h1> <p>Today is {new Date().toLocaleDateString()}</p> </div> ); }
Key Takeaways
JSX is not HTML—it’s syntactic sugar for
React.createElement()
.Combines JavaScript + Markup for expressive UI code.
Required for most React projects (though technically optional).