Lesson 3
20 min
Write markup inside JavaScript, insert expressions and learn the rules of JSX.
Definition
JSX (JavaScript XML) is aJavaScript syntax extension that allows you to describe a component's interface using HTML-like tags directly inside your code. Browsers do not understand JSX: a compilation tool transforms it into ordinary JavaScript calls before execution.
In the previous lesson, you wrote your first component that displayed a heading. You may have noticed that the heading was written directly inside JavaScript, without quotation marks: that is JSX. This lesson explains what this syntax is, why React uses it, which rules distinguish it from HTML, and how to insert values calculated by your code. By the end, you will be able to read any simple component and identify the most common syntax errors yourself.
Lesson Objectives
className, camelCase, and closed tags.JSX is a syntax that allows you to write HTML-like markup directly inside JavaScript code. It is not HTML: a compilation tool transforms it into JavaScript calls before the browser executes it. This allows React to combine a component's appearance and logic in the same place.
In the past, HTML and JavaScript were strictly separated. React follows a different idea: what matters is keeping related things together. A button, for example, has both an appearance and a behavior. With JSX, both belong to the same component, making the code easier to read and maintain. JSX is not required to use React, but almost every React project uses it because it is much easier to write than the function calls it replaces.
Here is a useful analogy: imagine a house blueprint. With traditional HTML, the blueprint (the structure) is in one document, while the construction instructions (the behavior) are in another. With JSX, each room comes with its blueprint and instructions in the same folder. When you want to modify the kitchen, you open just one folder and everything is right in front of you.
function App() {
return (
<div>
<h1>My First React Page</h1>
<p>This is JSX.</p>
</div>
);
}
export default App;In this example, theAppfunction returns a block of JSX placed inside parentheses afterreturn. The parentheses allow you to write JSX across multiple lines. Without them, JavaScript might consider thereturnstatement finished at the end of the line and return nothing. Each tag corresponds to an element that will appear on the screen, just like in HTML.
It is important not to confuse these three concepts because beginners often mix them up. The following list summarizes their roles.
When you start your project, a compilation tool (for example, Vite using a compiler such as Babel or esbuild) reads your files and replaces each JSX tag with a function call. You do not need to write these calls yourself, but seeing them once helps explain why JSX follows strict rules.
// What you write
const heading = <h1 className="large">Hello</h1>;
// What the compiler produces (simplified version)
const heading = React.createElement(
"h1",
{ className: "large" },
"Hello"
);TheReact.createElementfunction receives three pieces of information: the element type ("h1"), its properties (classNamein this case), and its content. It returns a JavaScript object describing the element. React then uses these objects to build and update what appears on the screen. In recent versions, the compiler uses a related function, but the principle remains the same.
This transformation explains several rules that might otherwise seem arbitrary. A component returns a single root element because a function returns one value. We writeclassNamebecause the property name becomes a key in a JavaScript object. And curly braces provide a way to say, "This is no longer markup; this is code."
Good to Know
You can use React without JSX by writing function calls directly. Almost nobody does this because the code quickly becomes difficult to read when a page contains several nested elements.
JSX looks like HTML, but there are a few important differences to remember:
classis a reserved word in JavaScript.onClick,htmlFor,tabIndex.Each rule has a reason. Fragments exist because a function returns one value: when several elements are next to each other, you need to group them without necessarily adding an unnecessarydivto the page.classNamereplacesclassbecause that word already has another meaning in JavaScript. Finally, camelCase follows JavaScript conventions: we writeonClick, notonclick.
This is one of the most common beginner mistakes. The first component below returns two elements next to each other: the compiler rejects this code and displays an error. The second example fixes the problem in two different ways.
function Page() {
return (
<h1>Heading</h1>
<p>Paragraph</p>
);
}// Solution 1: a div wrapping the elements
function PageWithDiv() {
return (
<div>
<h1>Heading</h1>
<p>Paragraph</p>
</div>
);
}
// Solution 2: a fragment that adds nothing to the page
function PageWithFragment() {
return (
<>
<h1>Heading</h1>
<p>Paragraph</p>
</>
);
}Which solution should you choose? If you need a container for styling or layout, use adiv. Otherwise, prefer a fragment: it avoids unnecessarily complicating the page structure. This can also prevent styling problems, especially in grids or tables where each additional nesting level matters.
The other three rules are often used together. The following code combines them in a small component. Notice the CSS class, thehtmlForattribute on the label, and the closing slash on theimgandinputtags.
function Profile() {
return (
<>
<img className="avatar" src="/photo.png" alt="My photo" />
<label htmlFor="name">Name</label>
<input id="name" type="text" />
</>
);
}In HTML, browsers may tolerate certain unclosed tags. In JSX, this is not allowed: the compiler must know exactly where each element starts and ends to generate its function calls. An element without content must therefore use a closing slash, such as<br />or<hr />.
Most HTML attributes are written the same way in JSX. Only some change their names, either because the original name is reserved in JavaScript or to follow camelCase conventions.
classbecomesclassName.for(on a label) becomeshtmlFor.onclickandonchangebecomeonClickandonChange.tabindexbecomestabIndex.data-*andaria-*attributes keep their hyphenated names.Inside curly braces, you can place anyJavaScript expression: a variable, a calculation, or a function call. React displays the result.
function Welcome() {
const firstName = "Aina";
const year = 2026;
return (
<div>
<h1>Hello, {firstName.toUpperCase()}!</h1>
<p>The year is {year}.</p>
<p>2 + 3 = {2 + 3}</p>
</div>
);
}An expression is a piece of code that produces a value: a variable name, an operation such as2 + 3, or a function call such asfirstName.toUpperCase(). Every time the component runs, React replaces the curly braces with the resulting value. If you change thefirstNamevariable, the displayed heading changes too. This is the first step toward interfaces that respond to data.

On the left, the Welcome component; on the right, what it displays in the browser.
Almost all JavaScript values can be used, but they do not all behave in the same way when rendered. The following list covers the most common cases.
{"Hello"}or{42}.{price * 2}.{student.name}.function Demo() {
const student = { name: "Rivo", age: 17 };
return (
<div>
<p>Name: {student.name}</p>
<p>Age: {student.age}</p>
<p>Boolean: {true}</p> {/* displays nothing */}
<p>Empty: {null}</p> {/* displays nothing */}
<p>Array: {[1, 2, 3]}</p> {/* displays 123 */}
</div>
);
}This behavior for empty values is intentional. In future lessons about conditions, it will allow you to show or hide elements based on information without writing complicated code. For now, remember that{true}and{null}produce no visible text.
When a calculation becomes long, it is better to move it outside JSX and place it in a function. JSX then stays short and readable, and the display code does not get mixed up with calculation details.
function formatPrice(amount) {
return amount.toLocaleString("en-US") + " Ar";
}
function Product() {
const name = "Notebook";
const price = 2500;
return (
<div>
<h2>{name}</h2>
<p>Price: {formatPrice(price)}</p>
<p>Price for 3: {formatPrice(price * 3)}</p>
</div>
);
}TheformatPricefunction is written once and reused twice in JSX. If you later want to change the display format, you only need to modify one place. This is exactly the spirit of React: small reusable pieces of code that can be combined.
Curly braces also work inside attributes. To apply inline styles, you use a JavaScript object. This explains the double curly braces: one pair for JSX and another for the object.
function Heading() {
const link = "https://react.dev";
return (
<div>
<a href={link}>Official Documentation</a>
<p style={{ color: "teal", fontSize: "20px" }}>Styled text</p>
</div>
);
}Notice two details in this example. First, a dynamic attribute value is written without quotation marks:href={link}, nothref="{link}". Second, CSS properties inside a style object use camelCase:fontSizeinstead offont-size. For more complex styling, CSS classes withclassNameare generally preferable.
There are two ways to write an attribute value. The rule is simple: if the value is fixed text, use quotation marks. If it comes from a variable or calculation, use curly braces. You cannot combine both syntaxes for the same attribute value.
function Link() {
const address = "https://react.dev";
const number = 3;
return (
<div>
{/* Fixed text: quotation marks */}
<a href="https://react.dev" title="Official Website">Link 1</a>
{/* Calculated value: curly braces */}
<a href={address} title={"Link number " + number}>Link 2</a>
{/* Numbers also use curly braces */}
<input type="text" maxLength={20} />
</div>
);
}The last example deserves an explanation:maxLength="20"passes the string "20", whilemaxLength={20}passes the number 20. Whenever you need to pass a non-string value, use curly braces.
Thestyleattribute is special: unlike HTML, it does not accept a CSS string. It expects a JavaScript object. CSS property names containing multiple words use camelCase, and string values are placed inside quotation marks.
// In HTML
// <p style="background-color: #f0f9ff; margin-top: 12px;">Hello</p>
// In JSX
function Card() {
const cardStyle = {
backgroundColor: "#f0f9ff",
marginTop: 12, // a number is converted to pixels
padding: "8px 16px",
borderRadius: "8px",
};
return <p style={cardStyle}>Hello</p>;
}You can store the object in a variable, as shown above, or write it directly inside the attribute using double curly braces. Unitless numbers are automatically interpreted as pixels for most relevant CSS properties, which explainsmarginTop: 12.
JSX handles text slightly differently from HTML. A few details deserve your attention to avoid unexpected display results.
{" "}.{"a < b"}.©displays the copyright symbol, while represents a non-breaking space.function FullName() {
const firstName = "Aina";
const lastName = "Rakoto";
return (
<p>
{firstName}{" "}
{lastName}
</p>
);
}Without{" "}, the two values would be joined together as "AinaRakoto". This technique is especially useful when two expressions appear on different lines because the line break between them does not necessarily produce a visible space.
function App() {
// A regular JavaScript comment before return
return (
<div>
{/* A comment inside JSX */}
<p>Some content</p>
</div>
);
}Inside JSX, you cannot use regular HTML comments or ordinary JavaScript comment syntax directly in the markup. Instead, place the comment inside curly braces using{/* ... */}. Beforereturn, however, you are writing regular JavaScript and can use//.
A useful tip: in VS Code, select a line of JSX and pressCtrl + /. The editor can automatically choose the appropriate comment syntax based on where the line is located, helping you avoid mistakes.
Good to Know
Inside curly braces, you can write an expression, which produces a value, but not a statement such as afor loop or an if statement. For conditions and loops, you will learn other techniques in a future lesson.
Here is a simple test: if you can putconst x = before your code and the resulting assignment is valid, you are generally dealing with an expression. Otherwise, it may be a statement. This is a useful beginner's rule for deciding what belongs inside JSX curly braces.
5 + 2,name.length, andgreet("Aina")are expressions, so they are allowed.if (x) { ... },for (...) { ... }, andconst a = 1;are statements, so they cannot be placed directly inside JSX curly braces.This does not mean you can never use conditions or loops. You simply write them beforereturn, where you are working with regular JavaScript, and then display their results using curly braces.
function Message() {
const hour = 14;
let greeting = "Good evening";
// Statement: allowed here, before return
if (hour < 18) {
greeting = "Hello";
}
return <h1>{greeting}!</h1>;
}In JSX, the first letter of a tag tells React what kind of element it represents. A tag beginning with a lowercase letterrepresents an ordinary HTML element, such asdivorp. A tag beginning with an uppercase letterrepresents a React component.
function Heading() {
return <h1>My Website</h1>;
}
function App() {
return (
<div>
<Heading />
<p>Welcome to my page.</p>
</div>
);
}In this example,<Heading />calls theHeadingcomponent and displays what it returns, while<p>is a regular HTML paragraph. If you wrote<heading />in lowercase, React would treat it as an HTML tag rather than your component. Component names must therefore begin with an uppercase letter.
What's Next?
The ability to combine small components is one of React's greatest strengths. In the next lessons, you will learn how to pass information to components using propsand make them interactive using state. The JSX you have just learned will form the foundation for all of this.
divor a fragment.imgorinputmust end with a closing slash.When your JSX is incorrect, the compiler displays an error in the terminal or browser. Do not ignore it: it usually tells you the file, line number, and nature of the problem. Here are two common messages and what they mean.
divor a fragment.imgtag without a closing slash.A good habit is to always fix the first error displayed. Later errors are often consequences of the first one, and they may disappear automatically once it is fixed.
Let's combine everything from this lesson in a single component. It uses a single root element, expressions, dynamic attributes, a style object, a comment, and a function call. First, read the entire example, then go through it line by line using the explanations below.
function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
function ProfileCard() {
const firstName = "aina";
const occupation = "computer science student";
const photo = "/images/aina.png";
const birthYear = 2005;
const currentYear = 2026;
const cardStyle = {
border: "1px solid #cbd5e1",
borderRadius: "12px",
padding: 16,
maxWidth: 320,
};
return (
<div className="card" style={cardStyle}>
{/* Photo: the attributes use variables */}
<img
className="avatar"
src={photo}
alt={"Photo of " + capitalize(firstName)}
/>
<h2>{capitalize(firstName)}</h2>
<p>{capitalize(occupation)}</p>
<p>Age: {currentYear - birthYear} years old</p>
</div>
);
}
export default ProfileCard;capitalizefunction defined above.classNameand a style object through a variable inside curly braces.srcandaltattributes are calculated from variables.You will notice that this component introduces no new concepts: everything it uses has already been covered in this lesson. If you understand every line, you have mastered the basics of JSX. Try changing the variable values and observe what changes in the browser. This is one of the best ways to check your understanding.
You will often need to take an existing piece of HTML and transform it into a React component. The method is always the same: go through the code and apply the rules of this lesson one by one. Let's start with a small form written in traditional HTML.
<div class="form">
<label for="email">Email address</label>
<input id="email" type="email" tabindex="1" required>
<br>
<button onclick="send()">Send</button>
<!-- The button triggers submission -->
</div>Here are the changes to make, in the order you would naturally notice them while reading the code from top to bottom:
classbecomesclassName.forbecomeshtmlFor.tabindexbecomestabIndex.inputandbrtags must be self-closing.onclick="send()"becomesonClick={send}, because you pass the function itself without parentheses.function Form() {
function send() {
console.log("Form submitted");
}
return (
<div className="form">
<label htmlFor="email">Email address</label>
<input id="email" type="email" tabIndex={1} required />
<br />
<button onClick={send}>Send</button>
{/* The button triggers submission */}
</div>
);
}Two details deserve your attention. First, writeonClick={send}rather thanonClick={send()}. With parentheses, the function would run immediately during rendering instead of waiting for the click. You will learn more about events in a future lesson. Second, therequiredattribute is accepted without a value in JSX: it is equivalent torequired={true}.
Beyond the mandatory rules, a few habits make your JSX easier to read, especially as your components grow.
firstNameis easier to understand than one namedp.ProfileCard.jsx.Test your understanding with these statements. Try answering before reading the corrections below.
ifstatement directly inside JSX curly braces.{2 + 3}displays the number 5.Answers: False (a compiler transforms JSX first); false (you need a parent or fragment); false (anifstatement is not an expression); true (the calculation runs and its result is displayed); false (React would treat the tag as an ordinary HTML element).
<> ... </>, that groups elements without adding anything to the page.fontSize.Exercise
App.jsx, create one variable for your first name and another for your age. Then display a sentence such as "My name is ... and I am ... years old" using curly braces. Also add a heading with a colored style.function App() {
const firstName = "Aina";
const age = 20;
return (
<div>
<h1 style={{ color: "teal" }}>Introduction</h1>
<p>My name is {firstName} and I am {age} years old.</p>
</div>
);
}
export default App;Exercise 2: Calculations in JSX
priceandquantity. Display the order total by multiplying them directly inside curly braces. Then add another line showing the total with a 10% discount.function Order() {
const price = 3000;
const quantity = 4;
return (
<div>
<p>Total: {price * quantity} Ar</p>
<p>With a 10% discount: {price * quantity * 0.9} Ar</p>
</div>
);
}Exercise 3: Dynamic Attributes
imgtag whosesrcandaltattributes use those variables. Then add a class usingclassName.function Photo() {
const address = "/images/landscape.jpg";
const description = "A mountain landscape";
return (
<img
className="photo"
src={address}
alt={description}
/>
);
}Go Further
<div class="box"> <img src="a.png"> </div>. Which JSX errors can you identify?// Error 1: class must become className
// Error 2: the img tag is not closed
function Box() {
return (
<div className="box">
<img src="a.png" alt="" />
</div>
);
}You may also notice that the image did not have analtattribute. This is not a JSX syntax error, but it is an important accessibility practice: always provide one, even if it is empty for a purely decorative image.
className, camelCase attributes, and properly closed tags.styleattribute expects an object whose properties use camelCase.{/* ... */}.