Ask questionsError: Invariant failed: You should not use <Switch> outside a <Router>
<!-- Thank you for contributing!
The issue tracker is meant for bug reports only. This isn't the best place for usage questions. Questions here don't have as much visibility as they do elsewhere. Before you ask a question, here are some resources to get help first:
The best bug report is a failing test in the repository as a pull request. Otherwise, please use the "BUG REPORT" template below.
Remove the template from below and provide thoughtful commentary and code samples on what this feature means for your product. What will it allow you to do that you can't do today? How will it make current work-arounds straightforward? What potential bugs and edge cases does it help to avoid? etc. Please keep it product-centric. -->
<!-- BUG TEMPLATE -->
5.0.1
I have a monorepo setup:
apps/
app1/
lib/
app.js <- webpack output
src/
App.tsx <- webpack entry
packages/
server/
src/
server.tsx
App.tsx
import { Switch, Route } from 'react-router-dom';
...
const App = () => (
<Switch>
<Route path="/" exact component={Home} />
</Switch>
);
export default App;
server.tsx
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import App from '../../../apps/app1/lib/app'; // Error: Invariant failed: You should not use <Switch> outside a <Router>
// import App from '../../../apps/app1/src'; // everything works as expected
...
renderToString(
<StaticRouter location={location} context={context}>
<App />
</StaticRouter>
);
...
No error is thrown
False positive error is thrown: "Error: Invariant failed: You should not use <Switch> outside a <Router>"
Answer
questions
timdorr
https://github.com/ReactTraining/react-router/issues/6789#issuecomment-502490351
Related questions