(react-router-dom
version: 4.1.1)
I have working routes set up, but I'm a bit confused about why the <Switch>
was necessary:
index.js
import React from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import App from './components/App.jsx';
import FridgePage from './components/FridgePage.jsx';
ReactDOM.render(
<HashRouter>
<Switch>
<Route exact path="/" component={App} />
<Route path="/fridge" component={FridgePage} />
</Switch>
</HashRouter>,
document.getElementById('root')
)
App.jsx
import Header from './Header.jsx';
import {Link} from 'react-router-dom';
export default class App extends React.Component {
render() {
console.log(this.props);
return (
<div>
<h1>Herbnew</h1>
<Link to="fridge">Fridge</Link>
{this.props.children}
</div>
);
}
}
FridgePage.jsx
import React from 'react';
export default class FridgePage extends React.Component {
render() {
return (
<div>
<h1>Fridge</h1>
You finally found the fridge!
</div>
);
}
}
I used to have a div
wrapping the routes instead of a Switch
. In that case, I see the App
rendered and try to click the Fridge link, but nothing happens (the FridgePage
isn't rendered), and no error is output into the console.
As I understand it, the only thing the Switch
does is exclusively render the first route it matches, and the common problem as a result of omitting it is rendering both pages at once. If my "/"
route is exact, then even without the Switch, the Fridge should be the only route that matches, right? Why does it not render at all?