Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  102] [ 2]  / answers: 1 / hits: 106489  / 6 Years ago, tue, may 29, 2018, 12:00:00

I have a problem that I don't know how to solve, I get this error when running npm test




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




What can the problem be and how can I solve it? The test I run is the standard app.test.js that comes with react



class App extends Component {
render() {
return (
<div className = 'app'>
<nav>
<ul>
<li><Link exact activeClassName=current to='/'>Home</Link></li>
<li><Link exact activeClassName=current to='/TicTacToe'>TicTacToe</Link></li>
<li><Link exact activeClassName=current to='/NumGame'>Quick Maths</Link></li>
<li><Link exact activeClassName=current to='/HighScore'>Highscore</Link></li>
<li><Link exact activeClassName=current to='/Profile'>Profile</Link></li>
<li><Link exact activeClassName=current to='/Login'>Sign out</Link></li>
</ul>
</nav>
<Switch>
<Route exact path='/' component={Home}></Route>
<Route path='/TicTacToe' component={TicTacToe}></Route>
<Route path='/NumGame' component={NumberGame}></Route>
<Route path='/HighScore' component={HighScore}></Route>
<Route path='/Profile' component={Profile}></Route>
<Route path='/Login' component={SignOut1}></Route>
</Switch>
</div>
);
}
};

More From » reactjs

 Answers
19

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>

[#54324] Friday, May 25, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leonardok

Total Points: 114
Total Questions: 94
Total Answers: 103

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;