chobo2
chobo2

Reputation: 85775

Why can't I use routers in React Router?

I am a bit confused on how to use react-router v4. The last time I used it I used v2 and it wasn't so different. I tried to follow some tutorials but I can't get it to work.

I get these two errors:

app.bundle.js:358 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

app.bundle.js:304 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
    at invariant (app.bundle.js:304)
    at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (app.bundle.js:17635)
    at ReactCompositeComponentWrapper.performInitialMount (app.bundle.js:32634)
    at ReactCompositeComponentWrapper.mountComponent (app.bundle.js:32525)
    at Object.mountComponent (app.bundle.js:4197)
    at ReactCompositeComponentWrapper.performInitialMount (app.bundle.js:32638)
    at ReactCompositeComponentWrapper.mountComponent (app.bundle.js:32525)
    at Object.mountComponent (app.bundle.js:4197)
    at mountComponentIntoNode (app.bundle.js:18399)
    at ReactReconcileTransaction.perform (app.bundle.js:6742)

My app looks like this right now:

import {BrowseRouter, Route, Switch, HashRouter} from 'react-router'

import MyComponent from './components/MyComponent';
    ReactDOM.render(
        <Provider {... stores}>
        <HashRouter>
            <MyComponent />
        </HashRouter>
    </Provider>, document.getElementById('root'));

I tried both BrowserRouter and HashRouter but same problems arises in both cases. I am using MobX which might be what is causing the problem. If I remove the routing stuff my component loads. How do I get this router stuff working?

Upvotes: 0

Views: 356

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

The problem is thatBrowserRouter and HashRouter are both part of the package react-router-dom -- not the core react-router (a change in v4) thus importing them from react-router will make them undefined thus the error when you try to create an element from undefined.

A huge change in v4 was to separate the different bindings for React Router into separate packages for organization, react-router-dom for DOM bindings, react-router-native for React Native bindings, etc, with react-router holding only the core. BrowserRouter and HashRouter are DOM bindings, thus the exist in the react-router-dom package.

Switch and Route also come from react-router-dom so import them from react-router-dom:

import { BrowserRouter, Route, Switch, HashRouter } from "react-router-dom";

Upvotes: 1

Related Questions