Setting up routes in your React Application with react-router-dom
— part 2/2
Now that our routes are working through URL’s path, let’s set up our NavBar just so our user can navigate between views without manually typing all those routes.
Inside the NavBar component file that you want to implement the navigation functionality, import NavLink component tag
from the react-router-dom and add the path each tag will be responsible to navigate by adding that as a prop
of your NavLink tag
.
And now we have a NavBar that dynamically changes routes.
Dynamic Routing
Now let’s learn how to use dynamic routes. In other words, routes that take place as your app is rendering, not in a configuration or convention outside of a running app.
For this part, we will build a simple application that renders all users on one page and by clicking in one specific user, the application will render a new component that loads all of the information for that specific user.
For that, let’s create a Route
with the component we want to render and add a path prop
that accepts a parameter.
Now, similar to what we did with the NavLink
, we are going to import Link
from the react-router-dom library and link that with the piece of data we want to enable dynamic route and pass the id
of the object — in this case, the user — to the Link component
as an argument of the URL.
Once you got this far, every time you click on Go to user’s page, React will render the page with the component you specified and the URL with the id
of the object that was clicked. In our case, we are going to have an URL looking like this:
Now, in order to grab the id from the URL and use it inside the component to fetch data only from that specific user we can use the following syntax:
const id = this.props.match.params.id
or make use of destructuring:
const {id} = this.props.params
and our function responsible to fetch data from our user would look something like the code bellow
Now, to be able to go back to the previous page all you have to do is access the props.history
of your component, and add the function goBack()
as an Event Listener.
And now you have a fully working application that loads component, without refreshing the page, using a NavBar and dynamic route.