Basic usage of the new React Router v6 (beta)

In this post we are going to look into how to use get started with the upcoming React Router version 6, currently in beta. Surely there are many more capabilities than those shown here, but this will get any app started, and might be enough for most of them.

Installation

To get started, install these packages:

This will install (at the time of writing) these package versions in your package.json:

The router component

For the sake of this example, we will create a few pages and we will see how to reach them, extract url parameters and search queries.

This is the code for my AppRouter component, which you will likely import at some point within your application (for example, in the App component)

Note: Your Navigation component needs to exist inside the router.

Links within the application

We will now use the Navigation component to reach those pages we created:

Here is how it looks like. As you can see it uses the Link component provided by the router.

How to use the URL parameters

In the Single page component, we can grab the URL parameter "id" and use it for whatever we need, like fetching some more data from some APIs.

How to use the location or query parameters

We have created a Search page which would show different search results according to search query parameters. In order to grab those parameters you do like this:

You can then use the locationSearch variable to extract the single parameters

So, that’s it! Hopefully this gave you a good starting point to implement React Router V6 in your app.

Leave a Reply

Your email address will not be published. Required fields are marked *