A Modular Approach To Routing With React Router 4

Jahdunsin Osho
iQube Bits
Published in
7 min readOct 24, 2017

What is react router ?

google search result for “what is react router”

Thank you so much freeCodeCamp!

In react, everything is component based, Which made React Router V4 a significant upgrade from the previous versions. A routes.js configuration file which is no longer needed was used to centrally manage the routing of a react application. Now everything with respect to react and routing is done using components.

I started building single page applications with Angular 2 all thanks to OMONIYI OLUWAFEMI (A chronic google enthusiast) who literally forced it on me. If you’ve also used Angular, you’ll notice everything is done in a modular structure. Related components are group into a common directory, CSS files of different components are separated, Even it’s route configuration files can also be split into modules. How to do these can be found in the glorious Angular documentation where you learn by building a web app for Heroes with Super Powers. Well the react documentation doesn’t have a step by step tutorial like angular does.

It is always best practice to split your project or code into modules. It makes your project organized (sexy), code easier to manage and bugs easier to find. In this article I’ll show you how to route a react web application and how to split these routes into modules.

Let’s Begin!

For this tutorial we’ll be using create-react-app. A lot of people prefer building their react projects by manually configuring webpack, But to keep things simple, We’ll be using create-react-app usually referred to as CRA.

This tutorial assumes you already have npm installed on your machine. Having said that, let’s start by installing create-react-app by running the following command from your terminal:

                    npm install -g create-react-app

Note: If you’re using the above command on linux, you might get an error at the end of the installation. Use sudo npm install -g create-react-app to install packages globally.

Let’s create a react application. To to that, run the following command in a directory of your choice.

               create-react-app react-router-tutorial
creating a new react app

The above command could take a few minutes depending on the speed of your internet connection. Done? Run the next set of commands to start the application.

              cd react-router-tutorial
npm start

It should launch your browser with the app running on your local server.

Next, Let’s install the libraries we’ll need to route in our application. Do this by running the following command.

         npm install react-router react-router-dom history --save

We’ll be using a report related application as a use case when creating our components. Open the project using any code editor of your choice and in the folder named “src”, create a file. Name the file app.routes.js, We’ll come back to this file later.

In the same src folder, Create a directory in it and name it components, This is where our components will live. For our project structure, we’ll name a directory after a component. Each component directory will contain the main component and it’s child components. Our first component will be a dashboard component which would serve as a parent for a “transactions component” for viewing recently made transactions and orders for recently completed orders. Don’t worry these are going to be extremely simple components. I just said all that for us to have a picture of how components can be used to build a real world web applications in react. Here’s a pictorial example of what I mean.

In the above image, we have dashboard as a subdirectory of the component directory. The dashboard directory contains a main component dashboard.component.js which serves as the parent component to the transactions and orders component. You’ll also notice a “dashboard.route.js” file, Well this is where we will manage routes within our dashboard component.

In react, there are two types of components, functional components and the class components. We’ll be making use of the class component, For more on types of components, have a look at the react documentation.

Let’s code our first react component, We’ll begin with the transactions and orders component . To do this, have your transactions component similar to the code snippet below.

import React, {Component} from 'react'class Transactions extends Component {
render() {
return (
<h1>Transactions Component works</h1>
);
}
}
export default Transactions;

In the code snippet above, we imported React and Component class from the react module. We then created a Transactions class which extends the Component class. This class has a render method which returns an HTML element. We then exported the Transactions class so it can be imported from other components, classes or any javascript code in our project. Copy the same code to the orders component and make the necessary switches.

Our transactions and orders components are done, Let’s move on to the dashboard route. The dashboard.route.js script should look similar to the code snippet below.

import React,{Component} from 'react';
import {Route} from 'react-router';
import Orders from './orders.component';
import Transactions from './transactions.component'

class DashboardRouter extends Component {
render(){
return (
<div>
<Route path="/orders" component={Orders}/>
<Route path="/transactions"
component={Transactions}/>
</div>
);
}
}

export default DashboardRouter;

Pretty similar to the Transactions and Orders component, the only differences are the Route which we imported from react-router and imported components which we created earlier, Nothing serious. We returned the Route component in the render method of our DashboardRouter passing it a path and a component. So when our browser matches these paths, the respective components passed to the routes would be rendered.

Now that we have our dashboard route ready, let’s move to our parent component, the dashboard component. What we’ll do in the dashboard component is basically what we did in the previous components. In the dashboard component though, we’ll be making use of NavLink from react-router-dom and DashboardRouter which we just finished coding up.Your dashboard component should look similar to the snippet below.

import React, {Component} from 'react';
import DashboardRouter from './dashboard.route';
import {NavLink} from 'react-router-dom';

class Dashboard extends Component {
render() {
return (
<div className="main">
<h4>React Router - Report App</h4>
<nav>
<NavLink
className="main-anchor"
to="/orders">
Orders
</NavLink>
<NavLink
className="main-anchor"
to="transactions">
Transactions
</NavLink>
</nav>
<div>
<DashboardRouter/>
</div>
</div>
);
}
}

export default Dashboard;

NavLink is just a way of navigating though our application in a declarative way. Using NavLink, our pages won’t need to reload to switch components. We could also use Link from the same react-router-dom library, NavLink though allows us add styles to our links. Speaking of styles, clear your App.css file and add the following styles to it. You can find the external style sheet in the root of the src directory.

h1, h4 {
text-align: center;
}

.main {
width:70%;
margin: 0px auto 0px auto;
}

.main-anchor {
text-decoration: none;
margin-right: 20px;
}

nav {
display: block;
width: 70%;
text-align: center;
margin-left: auto;
margin-right: auto;
}

Remember the app.route.js file we said we were going to get back to? Well it’s time. Let’s hook up our routes together, your app.route.js file should look similar to the code snippet below.

import React, {Component} from 'react';
import {Router, Route} from 'react-router';
import createHistory from 'history/createBrowserHistory';
import Dashboard from './components/dashboard/dashboard.component'

class AppRoute extends Component {
render() {
const history = createHistory();
return (
<Router history={history}>
<Route path="/" component={Dashboard}/>
</Router>
);
}
}

export default AppRoute;

We just created our AppRoute component where all parent components will be imported so they can be rendered on route match. We imported Router and Route from react-router and createHistory from history. The Router serves as the parent component for all individual routes available in our application. It takes a property history. History is an object passed to the Router to maintain the location of our react application.

One Final modification to our app and we’re done! In the App.js file located in the root of the src directory, we’ll import AppRoute and return it in it’s render method. Your App.js file should look similar to the code snippet below.

import React, { Component } from 'react';
import AppRoute from './app.route';

class App extends Component {
render() {
return (
<AppRoute/>
);
}
}

export default App;

Aaaaand we’re done! If you properly followed the steps through the course of this tutorial, you should have a working web application that looks like this.

Screenshot of the complete app

You should be able to switch between the orders and transactions component by using their respective links.

Conclusion

Together we’ve been able to learn best practices for organizing a react app.

We’ve learnt how to route a react application and successfully learnt how to split these routes into modules. Pheewwww!

Kindly suggest other best practices you use through comments, they will be very much appreciated. Thanks for staying till the end!

--

--

Jahdunsin Osho
iQube Bits

Software Engineer | Building edubaloo.com | I do content marketing for SaaS companies.