stef
stef

Reputation: 313

“React” undefined for React Router with Typescript

This is my React Router setup that I want to run through Typescript. It works without Typescript, but not with it. I get an runtime error in my browser console. Transpilation works fine though. It doesn’t make a difference if I include a “react.js” and “react-dom.js” seperately or a giant “bundle.js” with everything included. What am I doing wrong?

Error:

Router.js:91 Uncaught TypeError: Cannot read property 'Component' of undefined
// For context, the line says: React.Component
at Object../node_modules/react-router/es/Router.js (Router.js:91)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/Router.js (Router.js:2)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/BrowserRouter.js (BrowserRouter.js:11)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/index.js (index.js:1)
at __webpack_require__ (bootstrap:19)
at Object../src/index.tsx (index.tsx:3)
at __webpack_require__ (bootstrap:19)

Code:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch }  from "react-router-dom";

class App extends React.Component {
  render() {
    return (
        <Router>
        <Switch>
        <Route path="/test/" render={() => (
            <div>
                Test.
            </div>
        )} />
        <Route exact={true} path="/" render={() => (
            <div>
                Root page.
            </div>
        )} />
        </Switch>
        </Router>
    );
  }
}

ReactDOM.render(
    <App />,
    document.getElementById("root") as HTMLElement
);

Upvotes: 0

Views: 1082

Answers (2)

stef
stef

Reputation: 313

Okay.

The solution was to add "esModuleInterop": true to my tsconfig.json.

Additionally, "allowSyntheticDefaultImports": true allowed me to write import React from "react"; instead of import * as React from "react";.

Thanks everyone.

Upvotes: 1

Kevin Pastor
Kevin Pastor

Reputation: 801

The way you import React is the problem. You should replace all your importing statements with something like this:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

Upvotes: 0

Related Questions