Gentle Introduction to TSX

Understand the TSX file extension and how code is written in it.

What is TSX?

Ionic-React components are written in TSX, or at least the Ionic-React components. TSX is like JSX, but it uses TypeScript. If you have never seen JSX or TSX, it takes some getting used to. JSX is an extension to JavaScript that allows you to put HTML markup directly inside your code. Likewise, TSX is the same concept extended to TypeScript. Consider this code snippet:

const fruit = [
'Apples',
'Oranges',
'Grapes',
'Peaches'];
return (
<div>
<h1>Hello, Ionic</h1>
<p>Welcome to our app!</p>
<h2>Here are some fruits</h2>
<ul>
{fruit.map((f) => <li>{f}</li>)}
</ul>
</div>
);

Understanding the code

It starts with an array of fruits, which should appear normal to anyone familiar with JavaScript. But then, it immediately returns HTML. There is a <div> with an <h1>, a paragraph, an <h2>, and an unordered list.

Inside that unordered list is where things get a little more interesting. There is a reference to the fruit array, and it is calling a map function. The map function accepts an arrow function as its parameter, which in turn accepts each element as it iterates over the array.

Here, the array element is assigned the letter f. Each element of the fruit array gets mapped to an <li>, with the fruit of each element of the array.

Notice the curly braces surrounding the call to fruit.map. That is a sign to TSX that you are going to run some code here. Think of it as a replacement function.

This block inside the <ul> is going to get replaced with the execution of what is inside; the same thing happens inside of the <li>. Rather than display a constant value, it will evaluate the value of f, and replace the curly-brace expression with the value of f. This will become much clearer as you progress.

In the next chapter, you will generate an Ionic app and see this code in action.

Quick Quiz

1

What is TSX?

A)

TSX is an extension to Typescript that allows you to put HTML markup directly inside your code.

B)

TSX is an extension to JavaScript that allows you to put HTML markup directly inside your code.

C)

JSX is an extension to HTML that allows you to put TSX directly inside your HTML code.

Question 1 of 30 attempted