Part 1 & 2: Get Up and Running with #React and #TypeScript

The “Get Up and Running with React and TypeScript” series is made up of posts from chapters in my book “Hello React and TypeScript“. If you have questions, comments or corrections, please reach out to me in the comments or on Twitter @charleslbryant.

You can view the posts in this series on the Hello React and TypeScript category page.

If you haven’t heard, I have been writing a little book called “Hello React and TypeScript“. Its a simple book that chronicles the steps I took to learn how to develop a React application using TypeScript and ES6.

I’m going to post some of the chapters here on my blog. This will provide an easy reference for me because the chapters are really a reorganization of notes that I took as I learned writing React with TypeScript/ES6. It is my hope that these posts may be helpful for someone looking to learn.

I will post the chapters, but I won’t keep them in sync with the book. If you want the latest and greatest, please check out the free book.


To start this series off we will look at the code samples. In this first post we will look at two chapters: Setting Up Samples and Component Basics. If you haven’t used React or TypeScript, I recommend you actually try out the code to get a better feel for React and TypeScript. You can reach out to me in the comments below or on Twitter @charleslbryant.

You can view the posts in this series on the Hello React and TypeScript category page.


Setting Up Samples

https://charleslbryant.gitbooks.io/hello-react-and-typescript/content/SettingUpSamples.html

Requirements

All of the code samples have a couple requirements

  • npm package manager (Node 5.2.0 used in development)
  • IE 10+ or similar modern browser that supports the History API

This first sample is the source for the basic development environment. This includes the packages and automation that will be used in the samples.

Note – to get the latest version of packages and automation you should clone the repository from root, https://github.com/charleslbryant/hello-react-and-typescript.git . We will make updates as we move along with new samples so version 0.0.1 is only a starting point.

Source Code

https://github.com/charleslbryant/hello-react-and-typescript/releases/tag/0.0.1

Installing

To install a sample you need to run npm to get the required dependencies. You should open a console at the root path of the sample directory and run

npm install

Then

tsd install

These commands will install the required npm packages and TypeScript Typings.

Run the Sample

To run the samples, open a console at the sample directory and run

gulp

This will kick off the default gulp task to run all the magic to compile TypeScript, bundle our dependencies and code into one bundle.js file, and move all of the files need to run the application to a dist folder, open the index.html page in a browser, and reload the site when changes are made to source files.

Basic React Component

https://charleslbryant.gitbooks.io/hello-react-and-typescript/content/Samples/ComponentBasic.html

This is a very basic example of a single React component. We could make it even simpler, but this example is still basic enough to start with.

Source Code

https://github.com/charleslbryant/hello-react-and-typescript/releases/tag/0.0.2

src/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World</title>
	<link rel="stylesheet" href="css/bundle.css"/>
</head>
<body>
<div id="app"></div>
<script src="scripts/bundle.js"></script>
</body>
</html>

If you don’t understand this, I recommend that you find an introduction to HTML course online.

The important part of this file is

. We will tell React to inject its HTML output to this div.

src/main.tsx

/// <reference path="../typings/tsd.d.ts" />
import * as React from 'react';
import * as DOM from 'react-dom';

const root = document.getElementById('app');

class Main extends React.Component<any, any> {
 constructor(props: any) {
 super(props);
 }

 public render() {
 return (
<div>Hello World</div>
;
 );
 }
}

DOM.render(<Main />, root);

If you know JavaScript, this may not look like your mama’s JavaScript. At the time I wrote this ES6 was only 6 months old and this sample is written with ES6. If you haven’t been following the exciting changes in JavaScript, a lot of the syntax may be new to you.

This is a JavaScript file with a .tsx extention. The .tsx extenstion let’s the TypeScript compiler know that this file needs to be compiled to JavaScript and contains React JSX. For the most part, this is just standard ES6 JavaScript. One of the good things about TypeScript is we can write our code with ES6/7 and compile it as ES5 or older JavaScript for older browsers.

Let’s break this code down line by line.


/// <reference path="../typings/tsd.d.ts" />

The very top of this file is a JavaScript comment. This is actually how we define references for TypeScript typing files. This let’s TypeScript know where to find the definitions for types used in the code. I am using a global definition file that points to all of the actual definitions. This reduces the number of references I need to list in my file to one.


import * as React from 'react';
import * as DOM from 'react-dom';

The import statements are new in JavaScript ES6. They define the modules that need to be imported so they can be used in the code.


const root = document.getElementById('app');

const is one of the new ES6 variable declaration that says that our variable is a constant or a read-only reference to a value. The root variable is set to the HTML element we want to output our React component to.


class Main extends React.Component<any, any> {

class is a new declaration for an un-hoisted, stict mode, function defined with prototype-based inheritance. That’s a lot of fancy words and if they mean nothing to you, its not important. Just knowing that class creates a JavaScript class is all you need to know or you can dig in athttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes.

Main is the name of the class.

extends says that the Main class will be created as a child of the React.Component<any, any>class.

React.Component<any, any> is a part of the TypeScript typing definition for React. This is saying that React.Component will allow the type any to be used for the components state and props objects (more on this later). any is a special TypeScript type that basically says allow any type to be used. If we wanted to restrict the props and state object to a specific type we would replace any with the type we are expecting. This looks like generics in C#.


constructor(props: any) {
    super(props);
}

The contructor method is used to initialize the class. In our sample, we only call super(props) which calls the contructor method on our parent class React.Component passing any props that were passed into our constructor. We are using TypeScript to define the props as any type.

In additon to calling super we could also initialize the state of the component, bind events, and other tasks to get our component ready for use.


public render() {
    return (
<div>Hello World</div>
);
}

Maybe the most important method in a React component is the render method. This is where the DOM for our component is defined. In our sample we are using JSX. We will talk about JSX later, just understand that it is like HTML and outputs JavaScript.

JSX is not a requirement. You could use plain JavaScript. We can rewrite this section of code as

public render() {
    return (
        React.createElement("div", null, "Hello World")
    );
}

The render method returns the DOM for the component. After the return statement you put your JSX. In our sample, this is just a simple div that says Hello World. It is good practice to wrap your return expression in parenthesis.


DOM.render(<Main />, root);

Lastly, we call DOM.render and pass Main, the React component we just created, and root, the variable containing the element we want to output the component to.


That’s it, pretty simple and something we can easily build upon.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s