Begin React with Typescript

2022-02-22 — Written by Fabien Schlegel
#React#Typescript

These technologies are good choices to build strong and reliable web applications.

React is a powerful UI library created by Facebook to build front end applications.

Typescript is a language built on Javascript. If you've already learned Javascript, you won't be lost.

The good news is that all Javascript courses and tutorials can be used for Typescript. Typescript benefits rely on adding types to all the code you write.

The Environnement

Before you start playing with React and Typescript, you must install some tools.

Visual Studio Code

To write code, you need a text editor. With modern languages and, using an IDE (integrated development environment) can be a better idea to take advantage of advanced tools like autocompletion, linter, code formatting, code snippets, ...

Visual Studio Code includes TypeScript language support. It provides syntax and semantic highlighting.

This editor can show you intelligent code completion, hover info, and signature information so that you can write code more quickly.

It can suggest types for your code. It's very useful to type React components or hooks for example.

You can install Visual Studio Code from here.

Node

The second tool you need is Node. It's a JavaScript runtime built on Chrome's V8 JavaScript engine.

With Node, you'll be able to run your project in your local environment. Go here to find the way to install it for your operating system.

You can check Node install with this command. It must return the Node version.

node -v

NPM & NPX

For your project, you'll need packages. A package is one or more modules grouped.

Luckily Node comes with NPM (Node Package Manager), a tool to install them.

Install a package with NPM is easy :

npm install react

To help us, npm give us a command: NPX (Node Package eXecute). It will execute a command from a package. If the package isn't installed, it will search it on the NPM registry of packages and install it.

Create React App

Last but not least tool we need to begin with React and Typescript: Create React App.

Facebook provides this package to have the smallest configuration to begin a project.

With this tool, we'll begin our first React and Typescript project in a few minutes.

Begin a project

Now, we are ready to start.

First, we start a new project with these commands. Open your terminal, type the first command and wait until the end.

npx create-react-app my-app --template typescript
cd my-app
npm start

Type the second and the third.

It opens a new tab in your browser with the "hello world" example generated by Create React App.

Important files

Open the folder in Visual Studio Code. I'll give you some explanations about the files you are going to find.

Visual Studio Code

package.json

Like each NPM project, you'll find a package.json file. It describes your app, available scripts and the needed packages and their version.

tsconfig.json

The file tsconfig.json give the Typescript compiler all the configuration for your app. Create React App give us all we need to begin.

Browsers don't understand Typescript language. When we will deploy our code, the compiler will transform all our code into Javascript.

As you can see, files have two new extensions: ts and tsx. ts is for Typescript files and tsx for files with JSX inside.

JSX is a syntax extension to JavaScript. JSX let you describe the user interface of a component with an HTML like syntax.

src/index.tsx

The first file to inspect is index.tsx. This is the entry point of our app. React must be imported into it. Our main component App.tsx is imported here

src/App.tsx

Now, take a look at the App.tsx file. Do you see something strange?

No, because everything is normal. It's Javascript code. And all your Javascript code is valid in Typescript.

public/index.html

Another important file is in the public folder. This is index.html. The bundle generated by Webpack and the TypeScript compiler will be injected into this file.

And now we can edit

Create a new file in the src folder. Name it ItemsList.tsx. Add the code below and save your work.

import { FunctionComponent } from "react";

interface ItemsListProps {
  list: Array<string>;
}

const ItemsList: FunctionComponent<ItemsListProps> = ({ list }) => {
  return <ul>{list.map((item) =><li>{item}</li>)}</ul>;
};

export default ItemsList;

As you can see we have a statement called ItemsListProps. Typescript calls it an interface, it's the name for objects typing. These are the props we must pass as parameters of our component.

The props are named list and it's an array of strings.

Another interface you can see is FunctionComponent. This interface is imported from React. It's the return of the function, what we get when the functional component is executed.

FunctionComponent is generic and need an optional argument, the props of our function.

Don't stop on this advanced type. You'll study it later.

This is, in my opinion, one of the fundamentals of the developer's job. Accepting not to understand immediately, and just using. Mastering each concept will come with time.

Now we come back to the App.tsx. Erase all the code between the div with class name App and replace it with our item's list component like below and add the import.

import ItemsList from './ItemsList';

function App() {
  return (
    <div className="App">
      <ItemsList />
    </div>
  );
}

export default App;

As you can see, we've got a problem. The compiler say us that ItemsList required a property, our list of items.

We need props

Create a list of items , add it to the ItemsList like below and look at the result. You'll see our list in your browser.

import ItemsList from './ItemsList';

function App() {
const ourList = ['item1', 'item2', 'item3'];

  return (
    <div className="App">
      <ItemsList list={ourList} />
    </div>
  );
}

export default App;

Add a number to our list and look at the react app.

Type is incorrect

The compiler give us an error. In the ItemsList component, we says an array of string, a number isn't valid for this property. We can change our number to be a string or change our type for list to accept number.

The pipe symbol is a special character in Typescript. It's used to chain multiple types. In this case, we can change our type for list to accept number and string.

list: Array<string|number>;

Conclusion

Today, I hope you'll have a good experience with React and Typescript. You'll be able to create your first component with React and Typescript in a few minutes.

This post is the first in a series on the basics of React with Typescript. Check back or follow me on social media to find out what's next.

See you later!

© 2021 Fabien Schlegel