Routing In React

Edidiong Etok
Nur: The She Code Africa Blog

--

A great number of frontend applications are built with the most in-demand JavaScript Framework called React. However, unlike other frameworks, react does not have a built-in routing system. Thus, most developers use a standard library called React-Router to achieve routing.

React-Router is a client-side routing library for navigating different pages in a React application. This router helps to keep the UI in accord with the browser URL.

Prerequisite

To fully understand this article, you must have basic knowledge of:

Installation/Setup

React-Router only works in React projects. So, we should create a new react project. Run the code below to do so

npx create-react-app react-router-app
cd react-router-app
npm start

React-Router runs its dependencies using a package manager like npm or yarn. It is published to npm in different packages:

  • React-router: This contains most of the core functionalities of react-router.
  • React-router-dom: used for routing through many pages in a web application. It has everything from react-router and includes a few DOM-specific APIs.
  • React-router-native: used for routing in mobile applications. It incorporates everything from react-router and puts in a few APIs specific to React-Native.

When you import stuff, you should always import from either react-router-dom or react-router-native and never directly from react-router. Otherwise you may accidentally import mismatched versions of the library in your app.

Since this project focuses on routing for web applications, we will use react-router-dom. To install it, run:

npm install react-router-dom

or

yarn add react-router-dom

Main Components of React-Router

Some components of react-router are frequently used; let’s see what they are and how they are used.

  • BrowserRouter: This parent component wraps all the other members. It runs on a web browser. It caches the present location in the browser’s address bar using neat URLs and routes using the browser’s inbuilt history store.
  • Routes: This is an interface for declaring navigation in react-route. It is mainly used when routing through more than one page. Without using the <Routes> element, more than one route component can suit the URL path and display it simultaneously. React-routing v6 introduced the <Routes>and it replaced the <Switch> component used in previous versions.
  • Route: used to render a UI in React based on the current location. It is a child component of <Routes> and accepts pathas props.
  • Link: This creates links to different routes and navigation around the application. It works like the HTML <a> tag with an actual href attribute that points to the resource it’s linking to. Note: <Link reloadDocument> can be used to omit client-side routing and let the browser control the transition.
  • NavLink: This is a special kind of <Link> that is handy when creating a navigation menu. It shows when a tab is selected and provides a helpful environment for assistive technology like screen readers. A active class is added by default to the <NavLink>component when it is active. For styling purposes, style or className is passed as props. These props replace activeStyle and activeClassName in previous versions. Finally, a function can also be passed as a child to modify the content of the <NavLink> component based on its active state.

Now let’s see how to use these components in our project. In your App.js file, import each component from react-router-dom.

import {BrowserRouter, Routes, Route, Link} from "react-router-dom";

Next,

import {BrowserRouter, Routes, Route, Link} from "react-router-dom";

function App(){
return (
<BrowserRouter>
<div className="App">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route exact path="/about" element={<About />}></Route>
<Route exact path="/contact" element={<Contact />}></Route>
</Routes>
</div>
</BrowserRouter>
);
}

Let’s talk about the props passed in the <Route> tag.

  • exact: used to match the precise value with the URL and only renders the component if the URL matches the path.
  • path: this defines the pathname assigned to a component.
  • element: this references the component which will render on tallying the path.

Nested Routes

React Router has a powerful feature called nested routes. This feature lets developers route from page to page and allows a parent component to have full control of its child component. This means the routes of children components are defined in the parent component. We can have different layers of nesting. In our example, we will work with two layers.

Using our previous code, The About component will have a child component called Classes which will have a child called Class.

<Route exact path="/about" element={<About />}>
<Route exact path="/about/classes" element={<Classes />}>
<Route exact path="/about/classes/:className" element={<Class />} />
</Route>
</Route>

The Class route is a dynamic route /:className , meaning it changes with a change in the class name.

In App.js which is the base component, we will have the following code:

import React from "react";
import {BrowserRouter, Routes, Route, Link} from "react-router-dom";

function App(){
return (
<BrowserRouter>
<div className="App">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/about" element={<About />}>
<Route exact path="/about/classes" element={<Classes />}>
<Route exact path="/about/classes/:class" element={<Class />}
</Route>
</Route>
<Route exact path="/contact" element={<Contact />} />
</Routes>
</div>
</BrowserRouter>
);
}

In the code above, the Classes component is a nested route (child route) of the About component. The child inherits the parent’s path and then adds its path i.e /about/classes.

In the About.js component, we will define where the matching child route should be rendered using the <Outlet /> component. See the code below.

import React from "react";
import { Outlet } from "react-router-dom"

function About() {
return (
<div>
<ul>
<li>
<Link to"/about/classes">Classes</Link>
</li>
</ul>
<Outlet />
</div>
);
}

export default About;

In classes.js component, we first create a list of classes available, this can be gotten from an endpoint. Next, we loop through the list to display the classes. Since we have a nested route inside the component, we render it using the <Outlet />

import React from "react";
import { Link, Outlet } from "react-router-dom";

const classes = [
{ id: "year1", className: "Year 1" },
{ id: "year2", className: "Year 2" },
];

function Classes() {
return (
<div>
<h2>Classes</h2>

<ul>
{classes.map((c) => (
<li key={c.id}>
<Link to={c.className}>{c.className}</Link>
</li>
))}
</ul>

<Outlet />
</div>
);
}

export default Classes;

In the class.js file, we can get and display the respective class names using useParams hook from react-router.

import React from "react";
import { useParams } from "react-router-dom";

function Class() {
const { classId } = useParams();
return (
<div>
<p> Class: {classId}</p>
</div>
);
}

export default Class;

You can find the complete code on GitHub.

Conclusion

This article highlights the use of react-router in a react project. It explains in detail how to install, set up, and use the main components of react-router. These components include BrowserRouter, Routes, Route, etc.

Finally, this article gives a rundown on how to use nested routes. Nested routes are one of the most important features of react-router.

Happy Coding 😄

--

--

Edidiong Etok
Nur: The She Code Africa Blog

Software developer (Frontend). My mission is to explain technical concepts one article at a time. Follow me to get updated on my next blog post