Behind the scenes, JSX is compiled into regular JavaScript function calls. Writing <h1>Hello</h1> actually compiles to something like React.createElement("h1", null, "Hello") โ this is exactly why JSX rules differ from HTML in a few important ways covered below.
const name = "Ravi";
function App() {
return (
<div>
<h1>Hello, {name}</h1>
<p>Welcome to React.</p>
<p>2 + 2 = {2 + 2}</p>
</div>
);
}Anything inside curly braces {} is evaluated as a regular JavaScript expression โ variables, math, function calls, ternaries โ and the result is inserted directly into the rendered output.
A component can only return one single root element. Trying to return two sibling elements side-by-side causes a compile error:
// โ Error - two root elements
function Bad() {
return (
<h1>Title</h1>
<p>Text</p>
);
}
// โ
Wrapped in a Fragment - no extra HTML element added to the page
function Good() {
return (
<>
<h1>Title</h1>
<p>Text</p>
</>
);
}The empty <>...</> tags are a Fragment โ a way to group multiple elements without adding an unnecessary wrapping <div> to the actual page.
function App() {
return (
<>
{/* JSX comments look like this */}
<div className="container">
<img src="logo.png" />
<br />
</div>
</>
);
}JSX uses className instead of HTML's class attribute (because class is a reserved word in JavaScript), and self-closing elements like <img /> and <br /> always need the trailing slash.
Writing <div class="box"> instead of <div className="box"> doesn't crash your app, but it silently fails to apply the styling โ React simply ignores the unrecognized class attribute in JSX. This is one of the most common early mistakes for developers coming from plain HTML.
Write a component that displays your name, age, and the result of a simple calculation, all using curly brace expressions, wrapped correctly in a single root element.
function Profile() {
const name = "Alex";
const age = 22;
return (
<>
<h2>{name}</h2>
<p>Age next year: {age + 1}</p>
</>
);
}
export default Profile;
Q Can I put an if statement directly inside JSX curly braces?
No โ curly braces only accept expressions, not statements. You can use a ternary operator or logical && instead (covered fully in Chapter 9: Conditional Rendering), or compute the value before the return statement.
Q Why can't a component return two sibling elements without a wrapper?
JSX compiles to a single function call tree, and a function can only return one value. Fragments (<>>) solve this by grouping multiple elements into one without adding extra markup to the actual page.