close
address. Gaston Geenslaan 11 B4, 3001 Leuven
s.
All Insights

Using React Router v6 to navigate within your React applications

In this blog post we take a look at the new version of React Router to create our navigation implementation for our React applications at Craftworkz.

Written by
Benjamin Dendas
Full-stack Developer
Photographer: Lili Popper | Source: Unsplash
The outlet keyword is nothing new. Last year, we met it to render a template using ember.js, it’s nice to see it is available in React Router.

At the end of last year, I had a holiday of a week to cool down from the usual Scrum Master tasks that my job contains.

Lately i’m feeling motivated to get back into building software and started writing some code again. The objective was simple, create something I enjoy building on, but also expand my experience in React.

Within this blogpost, I would like to go over a few things how I implemented React Router v6 within my master-detail React application.

For this guide we use React v17 and typescript v4.

🛠 Installation

To install React router version 6, we use the following command:

npm install react-router-dom@6

📝 Defining routes with React Router v6

After installing the React Router package, we need to configure the routes. These routes will define the paths in our application. We will do this in the main file of the application App.tsx

The different routes that are being used are contained in a Routes wrapper which contains Route elements.

<Routes>     
<Route path="/" element={<Home />}/>
<Route path="/login" element={<Login />}/>
<Route path="/register" element={<Register />}/>
</Routes>

Every route has a path and and an element which specifies which component should be visualised and on what route it should appear.

Subroutes in React Router

Within a route you can define subroutes by nesting new route elements within existing route elements. Within our Routes section in App.tsx it looks like this:

<Routes>
<Route path="/overview" element={<Overview />}>
<Route path="settings" element={<Settings />}/>
<Route path="generate" element={<Generate /> }/>
<Route path="templates" element={<Templates /> }/>
</Route>
</Routes>

We can use subroutes to create a master-detail view within our application. For this to be possible in an easy way, React-Router version 6 introduced the outlet component. That component will render the child components within your application at the place where you define the outlet.

We use the outlet to be able to show a sidebar on one side of the screen and a detail window next to it. When you click on a navigation item, the correct subroute will be rendered.

The sidebar component that lives on the overview screen and contains three links that navigate to their specific subroute. It looks like this:

<div className="sidebar__container">
<Link className="sidebar__item" to="/overview/templates">Templates</Link>
<Link className="sidebar__item" to="/overview/generate">Generate</Link>
<Link className="sidebar__item" to="/overview/settings">Settings</Link>
</div>

In overview.tsx we see that we have an outlet JSX element, on that place, the subroute will be rendered by react.

<div className="overview__container">
<div className="overview__container__body">
<Sidebar />
<div className="overview__body">
<Navigation />
<Outlet />
</div>
</div>
</div>

The outlet keyword is nothing new. Last year, we met it to render a template using ember.js, it’s nice to see it is available in React Router.

🧭 Basic navigation with React Router

React router enables you to navigate through your application on different ways. Two of the main ways that I use within my applications are Link and useNavigate.

🔗 Link

In our HTML code we can use the Link element to navigate from the current url to another within our application. A Link element has a required to property where you can pass the path to to where you want to navigate towards. The path needs to match the routes that are defined in our App.tsx file.

An example of a Link statement looks like this:

<Link className="navigation__element" to="/login">Login</Link>

🪝 The useNavigate hook

React Router enables us to navigate from within our typescript code, this is done by using a hook that’s shipped with version 6 of React Router .

In v5 and lower, we used the useHistory hook to navigate from our application code to a new route with the push method. Starting with v6 the useHistory hook is replaced by the useNavigate hook.

We declare the useNavigate hook in our functional component and use the variable that we declared to navigate in our application.

let navigate = useNavigate();

In the following snippet you will see that the we use navigate as a method to navigate to the /overview route.

<Button type="submit" mode="success" onClick={() => navigate("/overview")}>Login</Button>

Using path parameters

When there is a page that is used to edit products you want to use the same URL multiple times but with another parameter. For that problem you use a path parameter.

We use path parameters when defining the routes in our application at app.tsx . React Router lets you define a parameter in a URL by prefixing it with :.

For example, when I have a command screen that lists all the commands of a bot, I would like to edit each command separately without the need to define more than one endpoint for it. Within our code it looks like this:

<Route path="/overview/command/:id/edit" element={<EditcommandPage />}/>

Our react app will build a url /overview/command/1/edit which React Router is smart enough to pick up due to the :id path parameter.

Our EditcommandPage can fetch the id that we passed and use it to fetch the actual data that’s available in our API. This is done by using the useParams hook that fetch the parameter out of the URL for us.

let { id } = useParams();

const navigate = useNavigate();
const [command, setCommand] = useState<CommandDto>();

useEffect(() => {
// fetch command
// ...
}, [])

Want to learn more?

Written by
Benjamin Dendas
Full-stack Developer

Subscribe to our newsletter

Raccoons NV (Craftworkz NV, Oswald AI NV, Brainjar NV, Wheelhouse NV, TPO Agency NV and Edgise NV are all part of Raccoons) is committed to protecting and respecting your privacy, and we’ll only use your personal information to administer your account and to provide the products and services you requested from us. From time to time, we would like to contact you about our products and services, as well as other content that may be of interest to you. If you consent to us contacting you for this purpose, please tick below:

By submitting this form, you agree to our privacy policy.

In order to provide you the content requested, we need to store and process your personal data. If you consent to us storing your personal data for this purpose, please tick the checkbox below.

More blog articles that can inspire you

what we do

Socials

address. Gaston Geenslaan 11 B4, 3001 Leuven