Router reaction
( react-router-dom
version: 4.1.1)
I have working routes set up, but I'm a little confused as to why I need it <Switch>
:
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>
);
}
}
Previously I used div
to wrap routes instead of Switch
. In this case, I see the render App
and try to click the Fridge link, but nothing happens (is FridgePage
not displayed) and no error is printed to the console.
As I understand it, the only thing that does Switch
is make only the first route it matches, and a common problem as a result of removing it is displaying both pages at the same time. If my route is "/"
accurate, then even without the switch, the refrigerator should be the only route that matches, right? Why isn't it showing at all?
source to share
<Switch>
returns only one first matching route.
exact
returns any number of exactly matching routes.
For example:
<Switch>
<Route exact path="/animals" component={Animals} />
<Route path="/animals/fish" component={Fish} />
<Route component={Missing} />
</Switch>
<Route path="/animals" component={Order} />
If the missing component is not inside <Switch>
, it will be returned on every separate route.
exact
, the "/ animals" route will not intercept all routes containing "/ animals", such as "animals / fish".
Without exact
, the route "/ animals / fish" will also return a Fish component for "animals / fish / cod", "/ animals / fish / salmon", etc.
Outside of the operator <Switch>
and without exact
, the Order component is displayed on every path containing "/ animals".
Usually, if you are not using exact, you would use a wildcard so that you do not return random pages.
source to share