Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Setting Up React and TypeScript

In this chapter, we will learn how to use both React and TypeScript together. We will start by going through the steps for creating a React and TypeScript project using a tool called webpack. Then we will create another project, but this time using a tool called Create React App to show you how to speed up the process of creating a React and TypeScript project.

This chapter will then cover how to use TypeScript to make React props and states type-safe, extending the alert component built in the first chapter. Lastly, we will learn how to debug your app with React’s DevTools.

In this chapter, we’ll cover the following topics:

  • Creating a project with webpack
  • Creating a project with Create React App
  • Creating a React and TypeScript component

Technical requirements

We will use the following technologies in this chapter:

All the code snippets in this chapter can be found online at https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition/tree/main/Chapter3.

Creating a project with webpack

Setting up a React and TypeScript project is tricky because both JSX and TypeScript code needs to be transpiled into JavaScript. In this section, we will cover how to set up a React and TypeScript project step by step, with the help of a tool called webpack.

Introducing webpack

Webpack is a tool that bundles JavaScript source code files together. It can also bundle CSS and images. It can run other tools such as Babel to transpile React and the TypeScript type checker as it scans the files. It is a mature and incredibly popular tool used in the React community that powers many React projects.

Webpack is incredibly flexible but, unfortunately, it requires a lot of configuration. We will witness this as we create our project with webpack.

It is important to understand that webpack isn’t a project creation tool. For example, it won’t install React or TypeScript – we have to do that separately. Instead, webpack brings tools...

Creating a project with Create React App

Create React App is a popular tool for creating React projects. It is based on webpack, so the knowledge from the last section will give you an understanding of how Create React App works. In this section, we will use Create React App to create a React and TypeScript project.

Using Create React App

Unlike the setup in the last section, Create React App generates a React and TypeScript project with all the common tools we will likely require, including CSS and unit testing support.

To use Create React App, open Visual Studio Code in a blank folder of your choice and run the following command:

npx create-react-app myapp --template typescript

npx allows npm packages to temporarily be installed and run. It is a common method of running project scaffolding tools such as Create React App.

create-react-app is the package for the Create React App tool that creates the project. We have passed it the app name, myapp. We have also specified...

Creating a React and TypeScript component

In Chapter 1, Introducing React, we built an alert component using React. In this section, we will use TypeScript to make the component strongly typed and experience the benefits. We start by adding a type to the alert component’s props and then experiment with defining a type for its state. After completing the alert component, we will inspect the component using React’s DevTools.

Adding a props type

We will continue using the React and TypeScript project created in the last section with Create React App. Take the following steps to add a strongly typed version of the alert component:

  1. Open the project in Visual Studio Code if it isn’t already open. Make sure you open the project in the app name folder so that package.json is at the root.
  2. Create a new file in the src folder called Alert.tsx. Paste in the JavaScript version of the alert component, which can be found on GitHub at https://github.com/PacktPublishing...

Summary

We started the chapter by creating a React and TypeScript project with the help of webpack and Babel. Lots of steps were involved and we only set up a fraction of what we would need for a real project. For example, we have not set up the ability to produce an optimized bundle for production.

We moved on to use Create React App for creating a React and TypeScript project. We saw how this approach is a much faster and more thorough way of creating a project. Then, we used ESLint for linting and Prettier for automatic code formatting. As a result of that exercise, we now understand how TypeScript, ESLint, and Prettier can be used together to create a high-quality React and TypeScript project environment.

In the final section, we learned how to create React components with strongly typed props and states. We experienced how this helps to catch problems quickly. We also played with React’s DevTools, which allows a React component tree to be inspected and the performance...

Questions

The following questions will check what you have learned in this chapter:

  1. What type will the name prop have in the following component, which has no type annotation?
    export function Name({ name }) {
      return <span>{name}</span>;
    }
  2. What type will the firstName state have in the following useState statement?
    const [firstName, setFirstName] = useState("");
  3. A ContactDetails component has the following type for its props:
    type Props = {
      firstName?: string;
      email: string;
    };
    export function ContactDetails({ firstName, email }: Props) {
      ...
    }

The preceding component is referenced in another component’s JSX as follows:

<ContactDetails email="fred@somewhere.com" />

Will a type error be raised?

  1. A status state variable can hold the "Good" and "Bad" values and is initially "Good". It is defined in the following code:
    const [status, setStatus...

Answers

Here are the answers to the questions in the preceding section.

  1. The name prop will have the any type.
  2. The firstName state will be given the string type because string will be inferred from the initial value "".
  3. There will be no type error even though firstName is not passed because it is defined as optional.
  4. The inferred type of status is string. An explicit type can be defined for the state using a generic type argument as follows:
    const [status, setStatus] = useState<'Good' | 'Bad'>('Good');
  5. The type for the FruitList component could be as follows:
    type Props = {
      fruits: string[];
    }

Alternatively, it could be defined using an interface as follows:

interface Props {
  fruits: string[];
}
  1. The email state could be defined as follows:
    const [email, setEmail] = useState<string | null>(null);

An explicit type needs to be defined; otherwise, an initial value of null...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon