React Using ReactJS with Typescript Installation and Setup


To use typescript with react in a node project, you must first have a project directory initialized with npm. To initialize the directory with npm init

Installing via npm or yarn

You can install React using npm by doing the following:

npm install --save react react-dom

Facebook released its own package manager named Yarn, which can also be used to install React. After installing Yarn you just need to run this command:

yarn add react react-dom

You can then use React in your project in exactly the same way as if you had installed React via npm.

Installing react type definitions in Typescript 2.0+

To compile your code using typescript, add/install type definition files using npm or yarn.

npm install --save-dev @types/react @types/react-dom

or, using yarn

yarn add --dev @types/react @types/react-dom

Installing react type definitions in older versions of Typescript

You have to use a separate package called tsd

tsd install react react-dom --save

Adding or Changing the Typescript configuration

To use JSX, a language mixing javascript with html/xml, you have to change the typescript compiler configuration. In the project's typescript configuration file (usually named tsconfig.json), you will need to add the JSX option as:

"compilerOptions": {
    "jsx": "react"

That compiler option basically tells the typescript compiler to translate the JSX tags in code to javascript function calls.

To avoid typescript compiler converting JSX to plain javascript function calls, use

"compilerOptions": {
    "jsx": "preserve"