Invariant Violation: You Should Not Use Outside A
Solution 1:
The error is correct. You need to wrap the Switch
with BrowserRouter
or other alternatives like HashRouter
, MemoryRouter
. This is because BrowserRouter
and alternatives are the common low-level interface for all router components and they make use of the HTML 5 history
API, and you need this to navigate back and forth between your routes.
Try doing this rather
import { BrowserRouter, Switch, Route } from'react-router-dom';
And then wrap everything like this
<BrowserRouter><Switch>
//your routes here
</Switch></BrowserRouter>
Solution 2:
The proper way to handle this, according to React Router devs, is to wrap your unit test in a Router. Using MemoryRouter
is recommended in order to be able to reset the router between tests.
You can still do something like the following:
<BrowserRouter><App /></BrowserRouter>
Then in App
:
<Switch><Route /><Route /></Switch>
Your unit tests for App
would normally be something like:
const content = render(<App />); // Fails Unit test
Update the unit test to:
const content = render(<MemoryRouter><App /></MemoryRouter>); // Passes Unit test
Solution 3:
Always put BrowserRouter in the navegations components, follow the example:
importReact, { Component } from'react'import { render } from'react-dom'import { BrowserRouter, Route, NavLink, Switch } from'react-router-dom'varComponente1 = () => (<div>Componente 1</div>)
varComponente2 = () => (<div>Componente 2</div>)
varComponente3 = () => (<div>Componente 3</div>)
classRotasextendsComponent {
render() {
return (
<Switch><Routeexactpath='/'component={Componente1}></Route><Routeexactpath='/comp2'component={Componente2}></Route><Routeexactpath='/comp3'component={Componente3}></Route></Switch>
)
}
}
classNavegacaoextendsComponent {
render() {
return (
<ul><li><NavLinkto="/">Comp1</NavLink></li><li><NavLinkexactto="/comp2">Comp2</NavLink></li><li><NavLinkexactto="/comp3">Comp3</NavLink></li></ul>
)
}
}
classAppextendsComponent {
render() {
return (
<BrowserRouter><div><Navegacao /><Rotas /></div></BrowserRouter>
)
}
}
render(<App/>, document.getElementById("root"))
Note: the BrowserRouter accept only one children element.
Solution 4:
Make sure to have correct imports in all nested components. You might get that error if one of them imports Switch from react-router instead of react-router-dom. Keeping everything consistent with 'react-router-dom' (that reexports react-router components anyway). Checked with:
"react-router":"^5.2.0","react-router-dom":"^5.2.0",
Solution 5:
The way I did was updating the dependencies with yarn add react-router-dom
or npm install react-router-dom
and deleting the node_modules folder and running yarn
or npm install
again.
Post a Comment for "Invariant Violation: You Should Not Use Outside A "