maiermic maiermic - 4 years ago 169
React JSX Question

How to install/import React in TypeScript

I try to get started with TypeScript and React. Since React is written in JavaScript, I install it using npm

npm install --save react

I need type definitions for React. So I tried

$ typings install react --save
typings ERR! message Unable to find "react" ("npm") in the registry. Did you want to try searching another source? Also, if you want contribute these typings, please help us:
typings ERR! caused by responded with 404, expected it to equal 200

I ran
typings search react
and found

react dt 2 2016-05-26T13:46:01.000Z

Hence, I explicitly specified the source

$ typings i dt~react --save
typings ERR! message Attempted to compile "react" as an external module, but it looks like a global module.

I can install React globally

typings install dt~react --save --global

but Atom still complains
Cannot find module 'react'
when I try to import React

import React from 'react'

How do you install React or configure TypeScript so that you can import React in TypeScript?

Answer Source

The React lib doesn't have a default export. So when you ask it to import React, it looks for a default export in that library. Unfortunately, it doesn't exist. Instead, import the whole contents and namespace in this way:

import * as React from 'react';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download