Lesson 3 / 1127%

Lesson 3

JSX

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

  • Explain what JSX is and what it is used for.
  • Understand what happens to JSX before it reaches the browser.
  • Apply the writing rules: root element, className, camelCase, and closed tags.
  • Insert JavaScript expressions using curly braces, both in text and attributes.
  • Write comments and avoid common mistakes.

What Is JSX?

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.

a component using JSX
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.

JSX, HTML, and JavaScript: What Does Each One Do?

It is important not to confuse these three concepts because beginners often mix them up. The following list summarizes their roles.

  • HTML: the markup language that browsers understand to display a page. It describes a fixed structure written manually in a file.
  • JavaScript: the browser's programming language. It performs calculations, makes decisions, and responds to user actions.
  • JSX: a way to describe what should be displayed directly inside JavaScript. The compiler translates it into regular JavaScript, and React then produces the actual HTML elements on the page.

What Happens to JSX Before It Reaches the Browser?

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.

the same element before and after compilation
// 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.

The Rules of JSX

JSX looks like HTML, but there are a few important differences to remember:

  • One parent element: a component must return a single root element. If you do not need a wrapper, use afragment, written as <> ... </>.
  • className instead of class:classis a reserved word in JavaScript.
  • camelCase attributes:onClick,htmlFor,tabIndex.
  • All tags must be closed: write <img />, <input />, and <br /> with a closing slash.

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.

Rule 1: A Single Root Element

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.

incorrect: two elements without a parent
function Page() {
  return (
    <h1>Heading</h1>
    <p>Paragraph</p>
  );
}
correct: using a div or a fragment
// 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.

Rule 2: className, camelCase, and Closed Tags

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.

example: fragment, className, and closed tags
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 />.

Important Attributes to Know

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.

Inserting JavaScript with Curly Braces

Inside curly braces, you can place anyJavaScript expression: a variable, a calculation, or a function call. React displays the result.

expressions in JSX
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.

Side-by-side screenshot: the Welcome component's JSX code in VS Code on the left and the result displayed in the browser on the right.

On the left, the Welcome component; on the right, what it displays in the browser.

What Can You Put Inside Curly Braces?

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.

  • Strings and numbers: displayed as they are, for example{"Hello"}or{42}.
  • Calculations and function calls: React displays the returned value, as in{price * 2}.
  • Arrays: each element is displayed one after another. You will learn how to transform an array into a list of elements in a future lesson.
  • true, false, null, and undefined: they display nothing. This is useful for conditions, which you will study soon.
  • Plain objects: they cannot be rendered directly. React throws an error because it does not know how to turn an object into displayable content. You must display one of its properties, such as{student.name}.
displayed values and ignored values
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.

Using a Function Inside Curly Braces

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.

moving a calculation outside JSX
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 in Attributes

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.

dynamic attributes and styles
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.

Quotation Marks or Curly Braces: Which Should You Use?

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.

fixed text or calculated 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.

Inline Styling in Detail

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.

from CSS to a style object
// 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.

Text, Spaces, and Special Characters

JSX handles text slightly differently from HTML. A few details deserve your attention to avoid unexpected display results.

  • Line breaks are generally collapsed: text written across multiple lines in the source is usually displayed on one line, with spaces handled similarly to HTML.
  • Leading and trailing spaces may disappear: to explicitly insert a space between JSX expressions, use{" "}.
  • The < and > characters need attention: the compiler may interpret them as part of a tag. To display them safely, put them in a string inside curly braces, for example{"a < b"}.
  • HTML entities work:&copy;displays the copyright symbol, while&nbsp;represents a non-breaking space.
displaying a space between two expressions
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.

Writing Comments in JSX

comments
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.

Expression or Statement: How Can You Tell the Difference?

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.

calculate before return, display inside JSX
function Message() {
  const hour = 14;
  let greeting = "Good evening";

  // Statement: allowed here, before return
  if (hour < 18) {
    greeting = "Hello";
  }

  return <h1>{greeting}!</h1>;
}

Components and HTML Elements: Capitalization Matters

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.

using a component inside another 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.

Common Mistakes

  • Returning multiple elements without a parent: wrap them in adivor a fragment.
  • Writing class instead of className: the application may still work, but React can display a warning in the console.
  • Forgetting to close a tag: tags such asimgorinputmust end with a closing slash.
  • Putting quotation marks around curly braces: dynamic values must be written without quotation marks; otherwise, they are treated as literal text.
  • Writing onclick instead of onClick: the lowercase attribute is not recognized as a React event handler, so the click will not trigger it.
  • Passing a string to style: this attribute expects an object, not an HTML-style CSS string.
  • Forgetting to capitalize a component name: React treats it as an HTML tag instead of your component.
  • Putting return alone on a line: without an opening parenthesis or expression on the same line, the function may return nothing.

Reading an Error Message

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.

  • "Adjacent JSX elements must be wrapped in an enclosing tag": you are returning multiple elements without a parent. Add adivor a fragment.
  • "Unterminated JSX contents": a tag is not properly closed somewhere. Look for an opening tag without its closing tag, or animgtag 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.

Complete Example: A Profile Card

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.

profile card: putting everything together
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;

Step-by-Step Explanation

  • Before return: this is regular JavaScript. We declare the data (first name, occupation, photo, and years), a style object, and use thecapitalizefunction defined above.
  • The root div: a single parent element contains the entire card. It receives a class throughclassNameand a style object through a variable inside curly braces.
  • The comment: it is placed inside curly braces and does not appear on the page.
  • The image: the tag is self-closing, and itssrcandaltattributes are calculated from variables.
  • The text: each pair of curly braces contains an expression (a function call or subtraction), and React displays the result in its place.

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.

From HTML to JSX: Converting Existing Markup

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.

before: 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.
  • Theinputandbrtags must be self-closing.
  • onclick="send()"becomesonClick={send}, because you pass the function itself without parentheses.
  • The HTML comment becomes a JSX comment inside curly braces.
after: valid JSX
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}.

Writing Best Practices

Beyond the mandatory rules, a few habits make your JSX easier to read, especially as your components grow.

  • Indent your code: move each nested element one level inward. This makes it easy to see which tag contains another.
  • Keep expressions short: if an expression becomes too long, move it into a variable or function outside JSX and display only the result.
  • Use one line per simple tag: when a tag has many attributes, put each attribute on its own line, as in the profile card's image.
  • Choose clear names: a variable namedfirstNameis easier to understand than one namedp.
  • One component per file: generally, each component has its own file, with a name beginning with an uppercase letter, such asProfileCard.jsx.

True or False?

Test your understanding with these statements. Try answering before reading the corrections below.

  • The browser executes JSX directly without transformation.
  • You can return two adjacent elements without a common parent.
  • You can write anifstatement directly inside JSX curly braces.
  • {2 + 3}displays the number 5.
  • A lowercase component name works the same way as an uppercase component name.

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).

Quick Glossary

  • Component: a function that returns JSX and describes part of a user interface.
  • Expression: a piece of code that produces a value and can therefore be placed inside curly braces.
  • Fragment: an empty wrapper,<> ... </>, that groups elements without adding anything to the page.
  • Compiler: a tool that transforms JSX into JavaScript that the browser can execute.
  • camelCase: a naming convention in which each word after the first begins with an uppercase letter, such asfontSize.

Exercises

Exercise

InApp.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.
suggested solution for exercise 1
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

Create two variables,priceandquantity. Display the order total by multiplying them directly inside curly braces. Then add another line showing the total with a 10% discount.
suggested solution for exercise 2
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

Create one variable containing an image URL and another containing its description. Display the image using animgtag whosesrcandaltattributes use those variables. Then add a class usingclassName.
suggested solution for exercise 3
function Photo() {
  const address = "/images/landscape.jpg";
  const description = "A mountain landscape";

  return (
    <img
      className="photo"
      src={address}
      alt={description}
    />
  );
}

Go Further

Mentally correct this code, then test it:<div class="box"> <img src="a.png"> </div>. Which JSX errors can you identify?
solution for the Go Further exercise
// 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.

Key Takeaways

  • JSX allows you to write HTML-like markup inside JavaScript. It is transformed before execution.
  • A component returns a single root element, which can also be a fragment.
  • UseclassName, camelCase attributes, and properly closed tags.
  • Curly braces insert JavaScript expressions into JSX, including inside attributes.
  • Thestyleattribute expects an object whose properties use camelCase.
  • A JSX comment is placed inside curly braces using{/* ... */}.
  • HTML elements begin with lowercase letters, while React components begin with uppercase letters.