Routing
React router docs can be found at https://reacttraining.com/react-router/web/guides/philosophy.
npm install --save react-router-dom
Let's modify our root component. First we need some declarations:
// at the top
import { BrowserRouter as Router, Route } from "react-router-dom"
Then we need to use Router
and Route
:
// wrap the main component in <Router />
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/help" render={() => <p>hi</p>} />
</div>
</Router>
)
}
}
Now run the app and see the difference between /
an /help
routes in the browser.
To actually render component, use the following syntax:
const Help = () => <p>Help...</p>
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/help" component={Help} />
</div>
</Router>
)
}
}
To use soft-links, use the Link
component found in react-router-dom
:
<Link to="/help">help</Link>
It is rendered as a simple a
tag, but it won't trigger page reload.
Home route and issues
Now let's add additional link for navigating to the root:
<ul>
<li>
<Link to="/">home</Link>
</li>
<li>
<Link to="/help">help</Link>
</li>
</ul>
What we want now is to render special component when we are not in a particular route - when we are actually on route /
:
<Route path="/" component={Home} />
<Route path="/help" component={Help} />
Let's see what happens in the browser when we navigate. Uh-oh! It seems that the Home
component is always being rendered! How can we render either one or the other one? It turns out that the matching needs to be improved so that the route /help
is not matched by the route /
.
Luckily, it is easy to fix by adding attribute exact
to the root route:
<Route path="/" exact component={Home} />
<Route path="/help" component={Help} />
Handling 404
To handle 404 we must tell our route definition "if you failed to match anything, render this". Which means we need to import yet another component from react-router-dom
: Switch
.
<Switch>
<Route path="/" exact component={Home} />
<Route path="/help" component={Help} />
<Route render={({location}) => <p>InvalidURL: '{location.pathname}'</p>} />
</Switch>