Understanding React Router with a Simple Blog Application
A practical introduction to one of the key react packages
React router is arguably one of the coolest feature there is in React. It is a famous library and familiarity in knowing how to use this library is expected for everyone who’s learning React. The reason is very simple. When using a website, it is essential for users to be able to view different pages seamlessly, or to navigate from one page to another. React Router is the library that makes this possible.
React creates single-page application and react router plays an important role to display multiple views without having to reload the browser in a single page application.
It is worth noting that it is almost impossible to display multiple views in React single-page applications without React Router. Websites that use react router for rendering multiple views for their app include, but not limited to Facebook, Instagram, Twitter, to mention a few.
This tutorial will be divided into two different sections. In the first section (part 1), we are going to learn some of the fundamentals of React Routing, as listed below:
- What is Routing?
- What is React Router DOM
- BrowserRouter, Route, Switch and Link simply explained
- And lastly, we will look at React router with hooks, focusing on useHistory, useParam, and useLocation.
In the second section (part 2), we are going to use all the knowledge we garnered in the first section to build a simple multi-page blog.
PART 1
What is Routing
Routing enables navigation from one view to another in a web application based on action or request. It is the ability to move from one page to another when a user click some element like link, button, icon, image, and so on within the application.
In other words, it is a process in which a user is directed to different pages based on their action or request.
React Router on the other hand, is used to create various routes in a single-page application. It is the standard routing package used in react to change views and move between pages.
For instance, when a user types a specific URL into the browser, the user is redirected to that particular route if the URL path matches any route inside the router file with the help of react router without the browser reloading.
To make use of React Router, we will need to use a package called React-Router-DOM. We will look at that in the next section.
What is React Router DOM
Now that we have a basic understanding of React Router, let’s take a cursory look at the React-Router-DOM. The React Router DOM is the node module that is specific to routing in web applications as opposed to mobile.
It allows engineers to create routes for a React single page application.
Simple enough. Next, let’s cover the components of react-router.
BrowserRouter, Route, Switch and Link
The BrowserRouter, Route, Switch and Link are all components of the React-Router. These components are divided into three categories.
The first category is routers, for example <BrowserRouter>
. The second category is route matchers, such as <Route>
and <Switch>
and the last category is navigation, such as <Link>
, and <Redirect>
Let’s take a look at each of these components individually.
<BrowserRouter>
: BrowerRouter is a router implementation that has the ability to incorporate routing in react. It uses the HTML5 History API which include pushState, replaceState and the popState event to keep our UI in sync with the URL. It is the parent component that is used to store all other components and it uses regular URL paths.<Route>
: Route is the conditional component that renders a component based on the URL defined or the URL it is pointing to. In other words, it is a component that renders some UI when its path matches the current URL.<Link>
: Link component is used to create links to different routes and implements navigation around the application. Links accepts theto
prop, which signifies where we want the link to navigate our user to.<Switch>
: The switch component is used to render only the first route that matches the location rather than rendering all matching routes.
Note: We will use all these components to build a simple blog application in a bit. Keep reading!!
Above all these powerful components, there are some very useful hooks that are really helpful by supplying additional information that we can use within our components. They are: useHistory
, useParam
, and useLocation
:
useHistory
According to the react router doc, the useHistory hook gives you access to the history instance that you may use to navigate. Through the history object, we can access and manipulate the current state of the browser history.
useParam
The useParam hook returns an object of key/value pairs of URL parameters where the key is the parameter’s name and the value is the parameter’s current value. In other words, it provides access to search parameters in the URL.
useLocation
The useLocation hook is equivalent to the useState but it returns a new location whenever the URL changes. In simple terms, the useLocation hook returns the location object that represents the current URL.
PART 2
Now it’s time to use the knowledge we’ve acquired in the first section to build a single page blog application so we can have a better understanding of routing in React. Our blog will have a navbar including the following functionalities:
- Signup/Login page
- Add new Post
- Show all post
- a toggle button to create a new post
- 404 page
And finally, we are going to use react router to link all of our pages together such that a user is able to seamlessly navigate between pages in our application.
To follow along, kindly clone the repo here and start the application on your local machine using npm start
You should see the screenshot below on your browser.
Now, its time for us to implement routing on our app to make it dynamic.
Let’s begin!
Step 1:
We need to install react-router-dom
via npm to handle the routing on our terminal by running:
npm install react-router-dom
Step 2:
Lets extract some code from our Home.jsx
file and create a new file: Navbar.jsx
.
Cut the following code snippets from your Home
component and paste it inside your Navbar.jsx
file
<h2>Nicole’s Blog.</h2>
<div className=’navbar__list’>
<ul>
<li>
Register
</li>
<li>
Login
</li> <li>
Write a Story
</li>
</ul>
</div>
Now, let’s update our Navbar.jsx
file by adding the following lines of code
import React from ‘react’;
import ‘../styles/Navbar.css’;
import {Link} from ‘react-router-dom’
function Navbar() {
return (
<div className=’navbar’>
<h2>Nicole’s Blog.</h2> <div className=’navbar__list’>
<ul>
<li>
<Link to=”/Login”>Login</Link>
</li>
<li>
<Link to=”/Register”>Register</Link>
</li>
<li>
<Link to=”/CreatePost”>Write a Story</Link>
</li>
</ul>
</div>
</div>
)
}
export default Navbar
Here, we imported Link
from react-router-dom
. Link
is just like an anchor tag <a>
with a real href
attribute in HTML. It has similar functionality and does the same thing like an anchor tag does.
So instead of using <a href>
here, we used Link to
. For example, on click of the Login button on the navbar, a user is redirected to the Login
page without the page refreshing or reloading. This applies to all the other links in the navbar.
Step 3:
Now it’s time to import all of our components into our App.js
file and see how we can use the categories we learnt in the first part of this article to make our blog app fully dynamic like so:
import {BrowserRouter, Route, Switch} from ‘react-router-dom’;
import Home from ‘./Components/Home’;
import Login from ‘./Components/Login’;
import Register from ‘./Components/Register’;
import CreatePost from ‘./Components/CreatePost’;
import AllPost from ‘./Components/AllPost’;
import Navbar from ‘./Components/Navbar’;
function App() {
return (
<BrowserRouter>
<div className=”App”>
<Navbar />
<Switch>
<Route exact path=’/’ component={Home}>
<Home />
</Route>
<Route exact path=’/Register’ component={Register}>
<Register />
</Route>
<Route exact path=’/Login’ component={Login}>
<Login />
</Route>
<Route exact path=’/CreatePost’ component={CreatePost}>
<CreatePost />
</Route>
<Route exact path=’/AllPost’ component={AllPost}>
<AllPost />
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
This is how we incorporated react-router into our application. First, we imported {``BrowserRouter, Route, Switch}
from 'react-router-dom'. Remember in the first part of this article we said <BrowserRouter>
has the ability to incorporate routing in react. That explains why we are wrapping all of our components that we want the routing to be in with it.
On line 12
, just before the Switch
component, we rendered the Navbar
component. This is because we want our navbar to be available to all our pages in our application.
We also used the Switch
component to render the first route that matches the location rather than rendering all matching routes. If we exclude the Switch
component from our code, all the routes will be rendered on a single page.
As we already know, the Route
renders a component base on the URL. In the above code, we gave the Routes
different path
depending on what we want it to render on our browser. We also specified the component by adding a prop, component
and setting it to the component we want to render.
Still on the Route
component, we used the exact
keyword to specify the exact path for specificity. Otherwise, whenever the Switch
component sees this /
in our URL, it will only render the first route just beneath it even though we specify the path we want rendered.
To better understand this, try removing the exact
keyword from the Route
component. Just play around with the code to gain more clarity.
On line 14-15
, we didn't specify the path to our route but we passed a prop Home
because we want to be able to render the Home
page when a user visits our page for the first time.
Open Source Session Replay
Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.
Happy debugging, for modern frontend teams — Start monitoring your web app for free.
REDIRECT
Next, let’s demonstrate a feature that will allow only logged-in or registered users to write a story on our blog.
We are going to do that inside our App.js
file using the Redirect
component like so:
import {BrowserRouter, Route, Switch, Redirect} from ‘react-router-dom’;<Redirect from=’/CreatePost’ to=’/Register’ />
This is very self-explanatory. Here, we imported the Redirect
component from the react-router-dom like the other component and on line 3, we are using it to redirect our user(a non-registered user in this scenario) to the Register
page when they try to write a story without registering/signing in first.
404 Page
Finally, let’s add a 404 page to our application such that if a user clicks or types a URL that isn’t on our app, such a user will be redirected to the page. Again, create a NotFound.jsx
file in your components folder and add the following code snippets:
import React from ‘react’
function NotFound() {
return (
<div>
<h1>404- Page not Found</h1>
</div>
)
}
export default NotFound
Next, import this file in your App.js
file and add the following:
<Route component=
{NotFound}>
</Route>
Let’s test this. When i try searching for a URL/page that doesn’t exist on our blog app, i got redirected to the 404 page like so:
Conclusion
In a nutshell, we looked at Routing in React from a beginner perspective by building a simple blog application. We also looked at react-router-dom and the different components with examples.
Hopefully, this article put you up to speed when building your next app.
You can find the code here- https://github.com/QNNAKWUE/react-blog
Thanks for reading!
Originally published at https://blog.openreplay.com on October 8, 2021.