Getting started with React.js and Typescript
Tags: react, typescript
Published: 2017-06-22 16:31:21

---
title: Getting started with React.js and Typescript
published: true
description: React.js is a Javascript UI library by Facebook. In this guide, we will wire it up with Typescript to display a "Hello World" on the browser page.
tags: reactjs, typescript
---

_I posted this originally in my [blog](https://jjude.com/react-with-tsc/)_

React.js is a Javascript UI library by Facebook. In this guide, we will wire it up with Typescript to display a "Hello World" on the browser page.

_Want to learn basics of Typescript? Read my [guide](https://www.jjude.com/ts/)_

![React with Typescript](https://cdn.jjude.com/react-tsc.svg)

I'm assuming you have already installed [node.js](https://nodejs.org/en/). In this post, I use [yarn](https://yarnpkg.com/) package manager from Facebook. But everything will work with [npm](https://www.npmjs.com), the default package manager for node.js.
 
It is a commonly accepted practice to have all the Typescript sources under a directory named `src` and compile final output in a directory named `build`. So let us create those directories.
 
Go to terminal and issue `mkdir src build`.

Let us initiate a new node.js project. `yarn init -y` comamnd will create a new node.js project with default values. We need to add few modules for our program. Let us add them. Issuse the following commands one by one.

```
yarn add react react-dom
yarn add -D typescript webpack ts-loader @types/react @types/react-dom

```

The -D in the second command indicates that the modules should be installed as development dependencies, which means they won't be installed in production. 

Let us understand the modules we have installed:

* `react` and `react-dom` are the core react modules. Without them, our program won't work;
* `typescript` is the superset of Javascript;
* `webpack` is a module bundler, which means it efficiently combines multiple Javascript files to create single Javascript file. This improves performance of the application.
* Webpack knows to combine Javascript files. But we are using Typescript. That's why we need `ts-loader`.
* `@types/react` and `@types/react-dom` contain type definitions for the `react` and `react-dom` modules.

By now, your `package.json` should look like this:
  

```
{
  "name": "01-react-tsc",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "author": "Joseph Jude",
  "scripts": {},
  "devDependencies": {
    "@types/react": "^15.0.30",
    "@types/react-dom": "^15.5.0",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.4",
    "webpack": "^3.0.0"
  },
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  }
}
```

We want to invoke `webpack` without prefixing with its path (`./node_modules/webpack`). Let us install it globally so that we can invoking it directly. Issue `yarn global add webpack`.

We need a config file to use `webpack`. Let us add the config file, named `webpack.config.js`. The config file is self-documented with comments.

```
var path = require("path");

var config = {
  /*
   * index.tsx represents the entry point to your web application. Webpack will
   * recursively go through every "require" statement in index.tsx and
   * efficiently build out the application's dependency tree.
   */
  entry: ["./src/index.tsx"],

  /*
   * The combination of path and filename tells Webpack what name to give to
   * the final bundled JavaScript file and where to store this file.
   */
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "bundle.js"
  },

  /*
   * resolve lets Webpack now in advance what file extensions you plan on
   * "require"ing into the web application, and allows you to drop them
   * in your code.
   */
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"]
  },

  module: {
    /*
     * Each loader needs an associated Regex test that goes through each
     * of the files you've included (or in this case, all files but the
     * ones in the excluded directories) and finds all files that pass
     * the test. Then it will apply the loader to that file.
     */
    loaders: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  },
  // When importing a module whose path matches one of the following, just
  // assume a corresponding global variable exists and use that instead.
  // This is important because it allows us to avoid bundling all of our
  // dependencies, which allows browsers to cache those libraries between builds.
  externals: {
    "react": "React",
    "react-dom": "ReactDOM"
  },
};

module.exports = config;

```

We need to add `tsconfig.json` file for Typescript. Copy paste the following code. If you have chosen to use different directory names, change these directory names in the `outDir` and `include` section.

```
{
  "compilerOptions": {
    "outDir": "./build/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react"
  },
  "include": [
    "./src/**/*"
  ]
}
```

Only one more step before we get into programming react.js library. We need to add a build step in the script section of `package.json`.

```
"scripts": {
  "build": "webpack"
},
```

Now we can run `yarn run build` and it will invoke webpack, which in turn will compile Tyepscript files and combine them into a single file.

Now that we have all the setup done, let us move on to create our application files.

Create an `index.html` in root directory with the following content. Here we are using the cdn version of `react` files. The `bundle.js` will be created by the webpack in the subsequent steps. Not the empty `div` tag with `main` as the `id`. This will be used by the react library to display the message -- for now, it is going to be `Hello World`.

```
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Getting started with ReactJS and Typescript</title>
</head>

<body>
  <div id="main"></div>

  <!-- we pick from cdn so can be cached by browsers -->
  <script src="https://unpkg.com/react@15/dist/react.min.js"></script>
  <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>

  <!-- compiled file for this project -->
  <script src="build/bundle.js"></script>
</body>

</html>
```

Let us create our logic file. Create `index.tsx` file in `src` directory.

```
import * as React from "react";
import * as ReactDOM from "react-dom";

ReactDOM.render(
    <h1>Hello World</h1>,
    document.getElementById("main")
);
```

Here we are importing the main modules of `react`. `ReactDom.render` has two parameters -- what to display and where to display. We are going to display `Hello World` as a title within `h1` tags. We are going to display it in the empty `div` that we created.

By now your directory structure should like like this:
  
```
.
â”œâ”€â”€ build
â”œâ”€â”€ index.html
â”œâ”€â”€ package.json
â”œâ”€â”€ src
â”‚Â Â  â””â”€â”€ index.tsx
â”œâ”€â”€ tsconfig.json
â”œâ”€â”€ webpack.config.js
â””â”€â”€ yarn.lock
```  

Time to execute. Issue `yarn run build` at the terminal. Now `webpack` will compile the application file and create `bundle.js`. If you open `index.html` in the browser, you will see `Hello World` as a header.

You can download the entire code from the [repository](https://gitlab.com/jjude/reactjs-exercises). Then run `yarn install` (or `npm install`) to install all the dependencies. Then execute with `yarn run build` (or `npm run build`).