Book Image

Learn React with TypeScript - Second Edition

By : Carl Rippon
4.4 (8)
Book Image

Learn React with TypeScript - Second Edition

4.4 (8)
By: Carl Rippon

Overview of this book

Reading, navigating, and debugging a large frontend codebase is a major issue faced by frontend developers. This book is designed to help web developers like you learn about ReactJS and TypeScript, both of which power large-scale apps for many organizations. This second edition of Learn React with TypeScript is updated, enhanced, and improved to cover new features of React 18 including hooks, state management libraries, and features of TypeScript 4. The book will enable you to create well-structured and reusable React components that are easy to read and maintain, leveraging modern design patterns. You’ll be able to ensure that all your components are type-safe, making the most of TypeScript features, including some advanced types. You’ll also learn how to manage complex states using Redux and how to interact with a GraphQL web API. Finally, you’ll discover how to write robust unit tests for React components using Jest. By the end of the book, you’ll be well-equipped to use both React and TypeScript.
Table of Contents (19 chapters)
1
Part 1: Introduction
6
Part 2: App Fundamentals
10
Part 3: Data
14
Part 4: Advanced React

Understanding JSX

JSX is the syntax we use in a React component to define what the component should display. JSX stands for JavaScript XML, which starts to give us a clue as to what it is. We will start to learn about JSX in this section and write some JSX in an online playground.

The following code snippet is a React component with its JSX highlighted:

function App() {
  return (
    <div className="App">
      <Alert type="information" heading="Success">
        Everything is really good!
      </Alert>
    </div>
  );
}

You can see that JSX looks a bit like HTML. However, it isn’t HTML because an HTML div element doesn’t contain a className attribute, and there is no such element name as Alert. The JSX is also embedded directly within a JavaScript function, which is a little strange because a script element is normally used to place JavaScript inside HTML.

JSX is a JavaScript syntax extension. This means that it doesn’t execute directly in the browser – it needs to be transpiled to JavaScript first. A popular tool that can transpile JSX is called Babel.

Carry out the following steps to write your first piece of JSX in the Babel playground:

  1. Open a browser, go to https://babeljs.io/repl, and enter the following JSX in the left-hand pane:
    <span>Oh no!</span>

The following appears in the right-hand pane, which is what our JSX has compiled down to:

React.createElement("span", null, "Oh no!");

We can see that it compiles down to a React.createElement function call, which has three parameters:

  • The element type can be an HTML element name (such as "span"), a React component type, or a React fragment type.
  • An object containing the properties to be applied to the element. Here, null is passed because there are no properties.
  • The content of the element. Note that the element’s content is often referred to as children in React.

Note

The right-hand panel may also contain a "use strict" statement at the top to specify that the JavaScript will be run in strict mode. Strict mode is where the JavaScript engine throws an error when it encounters problematic code rather than ignoring it. See the following link for more information on the strict mode in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.

You may also see /*#__PURE__*/ comments in the right-hand panel. These comments help bundlers such as webpack remove redundant code in the bundling process. We will learn about webpack in Chapter 3, Setting up React and TypeScript.

  1. Let’s expand our example by putting a div element around the span element, as shown in the following code snippet:
    <div className="title">
      <span>Oh no!</span>
    </div>

This now transpiles to two function calls to React.createElement, with span being passed in as a child to div:

React.createElement("div", {
  className: "title"
}, React.createElement("span", null, "Oh no!"));

We can also see a className property, with the "title" value passed with the div element.

Note

We have seen that React uses a className attribute rather than class for CSS class references. This is because class is a keyword in JavaScript, and using that would cause an error.

  1. Let’s do something really interesting now. Let’s embed some JavaScript within the JSX. So, make the following highlighted changes:
    const title = "Oh no!";
    <div className="title">
      <span>{title}</span>
    </div>

We declared a title JavaScript variable, assigned it "Oh no!", and embedded it within the span element.

Notice that the title variable is placed in curly braces inside the element. Any piece of JavaScript can be embedded within JSX by surrounding it in curly braces.

Our code now transpiles to the following:

const title = "Oh no!";
React.createElement("div", {
  className: "title"
}, React.createElement("span", null, title));
  1. To further illustrate the use of JavaScript in JSX, let’s use a JavaScript ternary expression inside the span element. Add the following ternary expression:
    const title = "Oh no!";
    <div className="title">
      <span>{title ? title : "Something important"}</span>
    </div>

A ternary expression is an inline conditional statement in JavaScript. The expression starts with the condition followed by ?, then what returns when the condition is true followed by :, and finally, what returns when the condition is false. For more information on ternary expressions, see the following link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator.

We see that the nested call to React.createElement uses the ternary expression as the child of span:

React.createElement(
  "span",
  null,
  title ? title : "Something important"
);

This completes our exploration of JSX in the Babel playground.

In summary, JSX can be thought of as a mix of HTML and JavaScript to specify the output of a React component. JSX needs to be transpiled into JavaScript using a tool such as Babel. For more information on JSX, see the following link: https://reactjs.org/docs/introducing-jsx.html.

Now that we understand a little more about JSX, we will create our first React component in the next section.