Getting Started with React
and TypeScript

yasith wimukthi
5 min readMay 12, 2022

--

Creating a react app

The most common and easiest way to start constructing a single-page application is with create-react-app (CRA). It’s also Facebook’s official boilerplate generator for making a beginner or simple React project. We can dive right into our code and create our React application using CRA because it uses a predefined webpack build for development. We don’t have to manually set up and configure our local development environment or production build.

Minimum requirements are Node >= 8.10 and NPM >= 5.6

First, in your terminal, check if you already have NPX:

$ npx -v

Or you can install it separately by running

$ npm install -g npx

NPX (Node Package Execute) is a feature of NPM that allows you to execute packages from the NPM registry without having to install them locally.

Now, let’s create our first create-react-app app with the following commands:

$ npx create-react-app <react-app-name> - - template typescript
cd <react-app-name>
npm start

The naming convention is to use small letters and a dash to separate the words. The — template TypeScript flag instructs CRA to use TypeScript as the default syntax and to apply the necessary customizations. Run <npm start> or <yarn start> to start your development server.

You can find the complete command scripts under “scripts” in your package.json. After running the command, check your app in your browser — http://localhost:3000 and and see the initial loading page of CRA with TypeScript as shown below.

Initial loading page of CRA with TypeScript

Let’s take a look at some of the files created by create-react-app.
Let’s start with the two most important files. Our app’s main page HTML template, public/index.html, includes React code and React to render context.
You’ll find the “root” here, which will allow JavaScript to operate the application. It’s also known as the React app’s mounting point:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8" />
<link rel=”icon” href=”%PUBLIC_URL%/favicon.ico” />
<meta name=”viewport” content=”width=device-width,
initial-scale=1" />
<link rel=”manifest” href=”%PUBLIC_URL%/manifest.json” />
<title>React App</title>
</head>
<body>
<section id="root"></section>
</body>
</html>

src/index.tsx holds the main render call from the React DOM. It imports our App.tsx component, which tells React where to render it:

import React from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import App from ‘./App’;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById(‘root’)
);

Some of the files and folders provided with CRA are defined and used in the following way:

node modules: It contains the JavaScript libraries as well as some of the libraries’ dependencies. Because this folder is fairly large, roughly 100mb–500mb depending on how many packages we’ve loaded in the app, we don’t usually include it in our Git repository.

public/manifest.json: This is a standard file that comes with CRA.
The configuration file is required for creating a Progressive Web App (PWA) from your existing React app.

src: The source code for the app’s user interface, including components and CSS styling. This is where the React app starts. App.tsx, our application’s entry point, and index.tsx, which bootstraps our app, are also visible.

package-lock.json: If you have Yarn installed on your computer, CRA will look for the Yarn package manager by default, but if it isn’t found, it will fall back to NPM. If you’re using Yarn, the yarn-lock.json file will appear instead.

package.json: It manages dependencies, scripts, versions, and other metadata of our project app.

tsconfig.json: This file in the directory root indicates that the said directory is the TypeScript project root.

Declaration Files for TypeScript with React

Declaration files also called .d.ts files are prefixed with ‘@types’. We avoid mishandling libraries and gain the ever-helpful and powerful “IntelliSense” or autocompletion in our editor by using declaration files (also known as definition files).

Let’s take a quick look at our package.json file to see the .d.ts files included with our CRA TypeScript template

@testing-library/jest-dom”:
“@testing-library/react”:
“@testing-library/user-event”:
“@types/jest”:
“@types/node”:
“@types/react”:
“@types/react-dom”:

We go to the DefinitelyTyped GitHub repo, where declaration files are maintained, to see if we require a declaration file (@types) for the library we just installed. Another option is to go to www.npmjs.com and type @types/ before the library name in the search box. Many individuals, thankfully, have already developed declaration files for the most widely used JavaScript libraries. If you fail to install an external library that requires a type declaration file, you will receive problems or your IDE will warn.

The Typings in TypeScrip

TypeScript’s typings are documentation in and of itself. Yes, it may appear to be a little extra effort at first, but it pays off in the long term with a substantial return. Many React developers who were skeptical at first now claim they can’t imagine not utilizing it.

Consider the following example. We explicitly define what type each variable is name is a string, age is a number, and so on:

name: string = "Jane Doe",
age: number = 18,
isStudent: boolean = true;

We need to specify our objects and data format in TypeScript. As a result, the compiler can intelligently search or detect our code, catching problems like calling a method with the wrong kind of argument or referencing a variable that isn’t present in the current scope.

React Function Components

React function components (React.FC) are JavaScript/ES6 functions that take parameters as component attributes and return valid JavaScript XML (JSX).
If necessary, it additionally accepts props as an argument.

The following is a simple function component with props:

const PrintMessage = props => {
return <div>{props.message}</div>
}

Let’s build a React function component now. Create a directory called components in the src folder, and a file called User.tsx in the components folder.

Before we go any further, let’s specify our props using TypeScript’s type aliases. The interface is another option, however we prefer to use the type alias to determine our properties:

import React from “react”;
type UserType = {
firstName: string;
lastName: string;
age: number;
};

It’s important to note that we built a User type to specify the properties that our components will use. The strings firstName and lastName are necessary, as is the integer age.

By creating a type, we can now then use it anywhere in our project as if it were a string, number, or any of the primitive or reference types.

Use the type Person as the model or shape of the props in our newly created
component. See the following:

const User = (props: Person) => {
const { firstName, lastName, age} = props;
return (
<div>
<h1> `Hello ${firstName}.`</h1>
</div>
);
};
export default User;

User is a stateless function component that takes a props object and destructures all of the UserType’s needed properties. Now that we have our function component with props, let’s get to our App.tsx to render it.

First, we need to import the component like so:

import Customer from “./components/User”;

And in our return call:

function App() {
return (
<div className=”App”>
<User
firstName=”John”
lastName=”Doe”
age={18}
/>
</div>
);
}
export default App;

let’s talk a bit more about React Hooks in next blog post.

--

--

yasith wimukthi

Associate Software Engineer | Software Engineering Undergraduate | Full Stack Developer