Routing
Routing Props
When react-router
renders a component, it passes routing-related props: history
, location
, and match
.
Pro tip: Another way to gain access to routing-related props is to use the higher-order component withRouter
.
Link Component
The Link
component basically renders an anchor component and prevents the default behaviour, re-rendering the DOM instead of navigating to the new link and losing state. Here's some useful tips...
You can pass an object instead of a string:
By default, the path you provide is absolute, appending it to the root domain. To make it relative, just use routing-related props:
If you want to add styling to your active links, use NavLink
instead:
Navigating programmatically
Sometimes, instead of using Link
to immediately navigate to a URL, we want to first run some code and then navigate to the URL.
In this case, we can programmatically navigate to a URL using the history
prop provided:
Note: Recall how browser history is like a linked list. By pushing to the end of the list, we're navigating to a new page by adding it to history.
Route Parameters
Suppose we want to display a blog post with the url https://blog.com/my-blog-post
, using my-blog-post
as the slug used to query the blog post contents.
Here's how we can access the parameter:
By marking our :slug
value as a dynamic value, we have access to slug
as a routing-related prop.
Using Switch
When implementing multiple Route
components, it's common to accidentally render more components than you want.
The Switch
component helps with this. Like the switch
statement, it renders the first Route
that matches the path visited:
Nested Routes
It's possible to have a Route
component inside another Route
component. However, it's important to understand that the parent Route
needs to remain rendered when you navigate to the child Route
.
The below example will not work because when you navigate to /:slug
, Blog
will unmount because the route doesn't match /blog
. And because the child Route
is part of Blog
, it will also unmount.
To solve this, it's better to utilize a relative path (as mentioned earlier). The below example will work because this.props.match.url
will include /blog
in the URL.
Last updated