TSX Fundamentals

By Syncfusion®, Inc. · Last updated

What TSX is and why React uses it, TSX syntax, the rules every TSX element follows, putting values inside { }, comments, rendering elements to the page, and Fragments.

TSX Introduction

TSX (TypeScript XML) lets you write HTML-like code inside a TypeScript file. Files that use it end in .tsx.

A React component uses TSX to describe what should appear on the screen. TSX is the TypeScript version of JSX (JavaScript XML).

Real-World Example

A product page in an online shop shows the title, price and stock of one book. The developer writes the layout once in TSX: <h2>{book.title}</h2> and <p>Price: ₹{book.price}</p>.

When the page loads a different book, the same TSX shows the new values. No HTML is copied or changed by hand.

TSX is HTML-like code inside TypeScript. It describes what a React component shows on the screen.

Why TSX?

Without TSX, you would build every element with a function call. TSX gives you a shorter way to write the same thing.

  • Easy to read — The code looks like the page it creates.
  • HTML and logic together — Values and conditions sit right next to the markup that uses them.
  • Type safety — TypeScript warns you about mistakes, such as a missing prop, before the app runs.
  • Helpful errors — The compiler points to the exact line of a broken tag.

TSX Is Turned Into JavaScript

The browser cannot read TSX. Before the app runs, the TypeScript compiler turns every tag into a plain JavaScript function call.

These two lines create the same heading:

// With TSX
const heading = <h1 className="title">Book Corner</h1>;

// What the compiler turns it into (simplified)
const heading = jsx("h1", { className: "title", children: "Book Corner" });

Every Run button in this course does the same thing: it compiles your TSX with the TypeScript compiler, then runs the result.

Animation: TSX code goes through the TypeScript compiler, becomes JavaScript, and the browser runs it

TSX<h1>Hi</h1>

TypeScriptcompiler

JavaScriptjsx("h1", ...)

Browsershows Hi The browser never sees TSX. It runs the JavaScript.

TSX is compiled to JavaScript before the browser runs it.

Introduction to TSX Syntax

A TSX element looks like an HTML tag. You can store it in a variable, return it from a function, or pass it to another function.

The variable welcome holds a TSX element. Writing {welcome} inside the <div> puts it on the page.

Multi-Line TSX

When TSX spans more than one line, wrap it in round brackets ( ). This tells TypeScript where the TSX starts and ends.

return (
  <div>
    <h1>Book Corner</h1>
  </div>
);

TSX Rules and Conventions

TSX looks like HTML, but it follows stricter rules. Breaking a rule gives an error when the code is compiled.

Rule 1: Return One Parent Element

A component must return a single element at the top. Wrap sibling elements in one parent, such as a <div>.

// Wrong: two elements at the top
return (
  <h1>Book Corner</h1>
  <p>Fresh books every week.</p>
);

The compiler stops with: JSX expressions must have one parent element.

Animation: two top-level elements cause a compile error; wrapped in a Fragment, they compile <h1>Book Corner</h1><p>Fresh books</p>Errormust have one parent <h1>Book Corner</h1><p>Fresh books</p><> ... </> FragmentCompiledone parent: the Fragment Step 1: two elements at the top, so the compiler stopsStep 2: wrap them in a Fragment, and it compiles

A component returns one parent. A Fragment groups the elements without adding a tag.

Rule 2: Close Every Tag

Every tag must be closed. Tags with no content, such as <img>, <input> and <br>, close themselves with />.

<img src="cover.png" alt="Book cover" />
<input placeholder="Search books" />
<br />

Rule 3: Use className Instead of class

class is a reserved word in JavaScript. In TSX, write className to add a CSS class.

Rule 4: Use camelCase for Attributes

Attributes with two words join them, with the second word capitalised. For example, onclick becomes onClick and tabindex becomes tabIndex.

Rule 5: Start Component Names With a Capital Letter

<BookCard /> is a component. <bookcard /> is treated as an unknown HTML tag.

The lab below follows all five rules.

Press Search in the preview. The console shows "Search clicked", because onClick connects the button to the function.

Try removing the / from <br /> and press ▶ Run. The compiler shows an error and names the line.

Embedding Expressions in TSX

Curly braces { } let you put a JavaScript value inside TSX. Anything inside the braces is worked out first, and the result is shown on the page.

You can put these inside { }:

  • Variables — {title}
  • Maths — {price * 2}
  • Function calls — {title.toUpperCase()}
  • Conditions — {stock > 0 ? "In stock" : "Out of stock"}

The last line shows "Out of stock" because stock is 0. Change stock to 5 and press ▶ Run.

Expressions in Attributes

You can also use { } for attribute values. Use quotes for fixed text and braces for values.

<img src={coverUrl} alt={title} />
<input maxLength={20} />

What You Cannot Put Inside

Only expressions work inside { }. An expression is code that produces a value. Statements such as if and for do not produce a value, so they cause an error.

// Wrong
<p>{if (stock > 0) { "In stock" }}</p>

// Correct
<p>{stock > 0 ? "In stock" : "Out of stock"}</p>

Inside { }, use a value, not an instruction. Use the ? : operator instead of if.

TSX Comments

Inside TSX, a comment goes inside curly braces: {/* comment */}. Outside TSX, in normal TypeScript code, use // as usual.

The preview shows only the heading and the paragraph. The comments are removed when the code is compiled.

Rendering TSX Elements

Rendering means showing a TSX element on the page. React needs two things for this: a place on the page, and the element to show there.

  1. index.html has an empty box: <div id="root"></div>.
  2. createRoot connects React to that box.
  3. render shows the element inside the box.
const root = createRoot(document.getElementById("root")!);
root.render(<App />);

The ! after getElementById(...) tells TypeScript that the element is sure to exist.

Animation: createRoot finds the empty root div, and render puts the App element inside it index.html<div id="root"> <App />the element root.render(...) WelcomeBook Corner 1. createRoot finds the box. 2. render puts the element inside it.

React shows your element inside the empty div id="root" box.

Rendering Updates the Page

Calling render again with a new element updates the page. React changes only the parts that are different.

The number goes up every second. Each call to render creates a new element, and React updates only the number.

In real apps, you call render once, for <App />. Components then update themselves with state, which you will learn in a later lesson.

Fragments in TSX

A component can return only one element. If you have two or more elements, you must put them inside one wrapper.

A Fragment is a wrapper that does not show on the page. You write it as <> at the start and </> at the end.

You can also use a <div> as the wrapper. But a <div> is added to the page as an extra tag. A Fragment adds nothing.

Comparison: a div wrapper adds an extra node to the page, a Fragment adds none With a div wrapperdiv.shelfdiv (extra)h2p3 tags: one extra div With a Fragmentdiv.shelfh2p<> groups them, then disappears2 tags: no extra node

A div wrapper stays on the page. A Fragment leaves nothing behind.

Look at the console. The <h2> and <p> sit directly inside <div class="shelf">. The Fragment left no tag of its own.

The Long Form: Fragment

Sometimes a Fragment needs extra information, called a key. React uses a key when you show a list of items. You will learn about it later.

The short form <> cannot hold a key. So in that case, use the long form: import Fragment from React and write <Fragment> and </Fragment>.

import { Fragment } from "react";

<Fragment key={book.id}>
  <dt>{book.title}</dt>
  <dd>{book.author}</dd>
</Fragment>

Easy Way to Remember: need a wrapper but no extra tag? Use <> and </>.

Common mistakes

MistakeWhat you seeFix
Returning two elements side by sideJSX expressions must have one parent element.Wrap them in <> and </> or a <div>
Leaving a tag open, such as <br>JSX element 'br' has no corresponding closing tag.Close it: <br />
Writing class="title"The class may not work, and TypeScript warnsWrite className="title"
Writing onclick in lower caseThe click does nothingWrite onClick
Putting if inside { }Expression expected.Use condition ? a : b
Writing a comment as <!-- -->The comment shows on the page or causes an errorWrite {/* comment */}
Forgetting { } around a variableThe page shows the word title, not its valueWrite {title}
Multi-line TSX without ( ) after returnThe component shows nothingWrap the TSX in ( )

Check Yourself

Exercises

What to Remember

  • TSX is HTML-like code in TypeScript. The compiler turns it into JavaScript before the app runs.
  • Use { } to put values in TSX, return one parent element, and close every tag.
  • Use a Fragment <> </> to group elements without adding an extra tag.

Next: Components