Home > Enterprise >  Error: Invariant failed: You should not use <Switch> outside a <Router> even though my s
Error: Invariant failed: You should not use <Switch> outside a <Router> even though my s

Time:12-12

I'm getting this error :

Error: Invariant failed: You should not use <Switch> outside a <Router>

But what's driving me crazy is the fact that My "Switch" tag actually is surrounded by "BrowserRouter"..

import {BrowserRouter, Route} from "react-router-dom";
import {Switch} from "react-router";
....
function App() {
    return (
        <AuthContext>
            <BrowserRouter>
                <div className="app">
                    <Switch>
                        <Route exact path='/login' component={Login}/>
                        <Route exact path='/register' component={Register}/>
                    </Switch>
                </div>
            </BrowserRouter>
        </AuthContext>
    );
}

When checking the router modules versions, I get this :

├─┬ [email protected] extraneous
│ └── [email protected] deduped invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router
├─┬ [email protected] extraneous
│ └── [email protected] deduped invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router
└── [email protected] invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router extraneous

CodePudding user response:

Currently it does not appear connected-react-router supports react-router-dom version 6.

├─┬ [email protected] extraneous
│ └── [email protected] deduped invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router
├─┬ [email protected] extraneous
│ └── [email protected] deduped invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router
└── [email protected] invalid: "^4.3.1 || ^5.0.0" from node_modules/connected-react-router extraneous

You are on the latest version of connected-react-router (6.9.2) and you can see here it still lists react-router-dom v4/5 as a peer dependency.

"peerDependencies": {
  "history": "^4.7.2",
  "react": "^16.4.0 || ^17.0.0",
  "react-redux": "^6.0.0 || ^7.1.0",
  "react-router": "^4.3.1 || ^5.0.0", // <-- not v6
  "redux": "^3.6.0 || ^4.0.0"
},

Though it seems there is possibly a plan to update connected-react-router to support react-router-dom version 6. There's some discussion here in connected-react-router's issue tracker with a possible work-around.

Outside of this possible work around if you've no pressing need, or desire, to use react-router-dom version 6 then I suggest reverting back to version 5. From your project's directory run the following commands to uninstall v6 and install v5.

  • npm uninstall -s react-router-dom
  • npm install -s [email protected] or any other specific v5.x version
  • Related