0

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
);

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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";

2 Comments

I had this before. Now I get these kinds of errors: ERROR in [at-loader] ./src/index.tsx:1:8 TS1192: Module '"/%path%/node_modules/@types/react/index"' has no default export.
Okay. I managed to to that via "allowSyntheticDefaultImports": true in my tsconfig.json but now I am getting the same error from my initial post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.