Write some code

Write some code

Let’s write our first TypeScript file using React. First, create a file named Hello.tsx in src/components and write the following:

import * as React from "react";

export interface HelloProps { compiler: string; framework: string; }

export class Hello extends React.Component<HelloProps, {}> {
  render() {
    return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
  }
}

Note that while this example is quite classy, we didn’t need to use a class. Other methods of using React (like stateless functional components) should work just as well.

Next, let’s create an index.tsx in src with the following source:

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

import { Hello } from "./components/Hello";

ReactDOM.render(
  <Hello compiler="TypeScript" framework="React" />,
  document.getElementById("example")
);

We just imported our Hello component into index.tsx. Notice that unlike with "react" or "react-dom", we used a relative path to Hello.tsx - this is important. If we hadn’t, TypeScript would’ve instead tried looking in our node_modules folder.

We’ll also need a page to display our Hello component. Create a file at the root of proj named index.html with the following contents:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
  </head>
  <body>
    <div id="example"></div>

    <!-- Dependencies -->
    <script src="./node_modules/react/dist/react.js"></script>
    <script src="./node_modules/react-dom/dist/react-dom.js"></script>

    <!-- Main -->
    <script src="./dist/bundle.js"></script>
  </body>
</html>

Notice that we’re including files from within node_modules. React and React-DOM’s npm packages include standalone .js files that you can include in a web page, and we’re referencing them directly to get things moving faster. Feel free to copy these files to another directory, or alternatively, host them on a content delivery network (CDN). Facebook makes CDN-hosted versions of React available, and you can read more about that here.

doc_TypeScript
2016-10-04 19:25:46
Comments
Leave a Comment

Please login to continue.