Web Programming TutorialsUsing Typescript in a React App

Using Typescript in a React App

In this article, you are going to learn how to quickly get started by building React applications that use TypeScript. For this demonstration, you are going to use create-react-app the official boilerplate for generating a new Reactjs project. TypeScript is a superset of JavaScript that provides additional layer as strongly typed programming language. It follows object-oriented programming concepts when compiled.

Pre-requisites

you must have installed:

  • Nodejs

  • npm/yarn

  • create-react-app version 2

Getting Started

If you do not have create-react-app installed, please run the command below in your terminal.

npm install -g create-react-app

If you have already installed it, please ignore the above step and let us begin. Invoke the create-react-app command with additional TypeScript option to generate a React application with TypeScript enabled. Now that Create React App v2 is out, official TypeScript support comes with it. To check which version you are currently on run the following command.

create-react-app --version
# output
2.1.1

create-react-app by default uses yarn as the package manager to install required dependencies. This is an exciting thing for JavaScript users that use TypeScript We are going to use yarn too to avoid context switching. If you have used create-react-app before, this should look very familiar. The additional piece of information is adding the –typescript flag. This flag tells CRA to use TypeScript as the default syntax and add the appropriate configuration to make it work out of the box.

You will get the first hands-on experience with TypeScript in your React project by looking at the project structure. Open the newly generated folder in your favorite code editor. You will see the following.

react app

Notice how the file extensions of App component is automatically changed to .tsx from the usual .js or .jsx. There is also .tsconfig file with rules and configuration. It sits at the root of a TypeScript project and indicates the compiler settings and files to include.

You can now run the application by running the command yarn start. You will be welcomed by the following welcome screen.

react app

The main advantage TypeScript provides is that it is a statically typed. Programming languages can either be statically or dynamically typed. The difference is when type checking occurs.

The App.tsx File

Let’s jump into the main App file that usually is our main React component. You would not find any TypeScript enabled source code here.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;

It is the same as the good old App.jsx file.

Create a TypeScript Component

In this section, let us create our first TypeScript Component. Inside App.tsx add the following above the class App.

function Greetings({ greetMessage }) {
return <div>Your message {greetMessage}!</div>;
}

This is a bare minimum class component which takes greetMessage from props. Simple React and JavaScript stuff. At this point, you will be getting a compilation error both in your code editor and in terminal.

react app

react app

Now let us modify this function and TypeScript and make this error go away.

function Greetings({ greetMessage }: { greetMessage: string }) {
return <div>Your message {greetMessage}!</div>;
}

We are defining in above that the prop greetMessage should be a string. This is called an inline way of defining a type. There are different ways to use TypeScript and described types. One can be if you create an interface as a separate object.

interface greetMessageProps {
greetMessage: string;
}

And then use them in the function Greetings like below.

function Greetings({ greetMessage }: greetMessageProps) {
return <div>Your message {greetMessage}!</div>;
}

This step includes a lot of boilerplate code writing. We are going to stick with the first option we used, that is inline types.

Using the TypeScript Component

So far our App.tsx file looks like below.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
function Greetings({ greetMessage }: { greetMessage: string }) {
return <div>Your message {greetMessage}!</div>;
}
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App

Let us the newly created TypeScript stateless component in the App. After the <a> tag, add:

<Greetings greetMessage="Hello World" />

Now visit the URL http://localhost:3000/ to see it in action.

This shows our props are well working. On passing the wrong type of prop, say if you try to pass a number, React would not even compile. That is the advantage TypeScript gives you. To catch errors like these in development mode. Change the value of greetMessage in Greetings from Hello World to {234}.

<Greetings greetMessage={234} />

First of all, you will be notified by the code editor that it expects a string instead of a number.

Next, visiting the URL http://localhost:3000/ in the browser window, where the app is compiling, it will display a similar error message.

Conclusion

And that is all you need to get started with React and TypeScript. Your application should now have the new features and be fully running with TypeScript. This only scratches the surface of what TypeScript provides us. You can create types for all your components and props and catch the errors faster, even before the React app compiles.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -