How to smoothly navigate between components
We have seen how to use the BrowserRouter
and Route
components to display different React components in different views.
We have seen how we can access different views by entering URLs in the browser address bar.
But users typically expect to be able to click on links to go to different web pages, so I am going to show how to implement this functionality in our web application.
It's very simple.
The react-router-dom
library that handles routes also makes available a component called Link
that we can use to create hyperlinks in our documents.
We must first import Link
from the library.
import { Link } from 'react-router-dom';
Let's suppose we want to create a link to the path /pokemons
that displays the Pokemons
component.
First we need to make sure we have a route for the /pokemons
path. The route would look like this:
<Route path="/pokemons" component={Pokemons} />
Then we add the link to this path with the Link
component. We can do it in this way:
<Link to="/pokemons" >Pokemons</Link>
The Link
component has a to prop that is set to the path we want to load in our application. We would use the same value as the Route component path prop.
Link will create an HTML <a>
tag on our page and set the href property of the <a>
tag to the location we specify.
The exact
prop
One thing to note is that the Link
and Route
components use regular expressions to match paths. This may lead to confusion if we have more than one path in our application with the same string in it.
For example, we may have these two links in our application (and relative routes):
<Link to="/pokemons" >Pokemons</Link>
<Link to="/pokemons/pikachu" >Pikachu</Link>
When we click on the second link, we might expect to see the Pikachu page, but we will see the Pokemons page instead. Why?
Because the regular expression engine will try to match the string /pokemons
and this string is present in both routes, so the first one will be matched first and the wrong component will be loaded.
We have a way to specify an exact match, though, so the correct route will be taken.
We simply include the exact
prop in our links. This will make the regular expression match only if the exact path is matched, so it will eliminate any ambiguity.
Here's how we use the exact
prop:
<Link exact to="/pokemons" >Pokemons</Link>
If we specify the link this way, only the route with the exact path of /pokemon
will be matched and we will be able to reach both the Pokemons and the Pikachu pages correctly.
Top comments (0)