How to setup Material-UI for React with Typescript?

René Stalder picture René Stalder · May 12, 2016 · Viewed 30k times · Source

I've run in some problems add Material UI to my React project, which is programmed with Typescript.

According to the tutorial, I start with adding the react-tab-event-plugin first.

import injectTapEventPlugin from 'react-tap-event-plugin';

// Needed for onTouchTap
// Can go away when react 1.0 release
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

Doing this, I get an error about the missing default export.

ERROR in ./src/index.tsx
(4,8): error TS1192: Module ''react-tap-event-plugin'' has no default export.

Adding Material UI

import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

Throws following build error

ERROR in ./src/containers/index.tsx
(8,25): error TS2307: Cannot find module 'material-ui/styles/getMuiTheme'.

ERROR in ./src/containers/index.tsx
(9,30): error TS2307: Cannot find module 'material-ui/styles/MuiThemeProvider'.

My Webpack Config is quite easy and did work with every React npm modul when I added the typings, until now.

Typing for both, react-tap-event-plugin and Material-UI are installed.

What's wrong?

Answer

René Stalder picture René Stalder · May 24, 2016

@types/material-ui is now available, exported from its DefinitelyTyped source.

npm install @types/material-ui --save-dev

npm install @types/react-tap-event-plugin --save-dev

Afterwards, you can do following:

import * as injectTapEventPlugin from 'react-tap-event-plugin';

// Needed for onTouchTap
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

Then use Material UI like this:

import * as React from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {MuiThemeProvider, lightBaseTheme} from "material-ui/styles";

const lightMuiTheme = getMuiTheme(lightBaseTheme);

class Root extends React.Component<any, any> {
  render() {
    return (
      <MuiThemeProvider muiTheme={lightMuiTheme}>
        <MyComponent/>
      </MuiThemeProvider>
    )
  }
}

The MyComponent would consume Material UI as defined in the docs:

import RaisedButton from 'material-ui/RaisedButton';

const MyComponent = (props:MyComponentProps) => {
  return (
      <RaisedButton label="Default" />
  )
}

export default MyComponent;

2016-08-08: Answer updated due to state change of the package.

2017-01-03: Add ref. to @types /qvazzler