React routing using React-router (NPM)

Musab Abbasi
6 min readNov 24, 2021

--

Routing allows user to navigate to different pages on a website/application by typing the url or navigate through a link.

We will be using React-router in this article as it is one of the most popular and easiest way of routing in React.js

What is React-router?

The react-router package is the heart of React Router and provides all the core functionality for both react-router-dom and react-router-native.

If you’re using React Router, you should never import anything directly from the react-router package, but you should have everything you need in either react-router-dom or react-router-native. Both of those packages re-export everything from react-router.

If you’d like to extend React Router and you know what you’re doing, you should add react-router as a peer dependency, not a regular dependency in your package.

Prerequisite:

To follow along with this tutorial you should have basic knowledge of React.js, HTML, React components and basic routing concepts.

Getting Started:

First we need to create a React.js app by executing the below command:

npx create-react-app frontend

I am naming our app as frontend so it will be easier to differentiate between backend and frontend if we make backend in future.

Now once its created lets clear our main component i.e. App.js in our frontend folder.

import React from "react"function App() {return (<div className=""></div>);}export default App;

Once its created, lets make a folder in src called as components. We will be putting all components in this folder. Now create a component inside this folder and name this component as Navigation.jsx.

Now import Bootstrap CSS and JS CDN into our root html file i.e. index.html.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#000000" /><metaname="description"content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /><link rel="manifest" href="%PUBLIC_URL%/manifest.json" /><title>React Routing</title><!-- Bootstrap CSS CDN  --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><!-- Bootstrap JS CDN  --><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script></body></html>

Now install react-router that will help us with creating routes in our React app.

npm install react-router-dom

Now run the react.js application by typing the below command

npm start

Now add bootstrap Navigation bar in our navigation.jsx component.

import React from "react";function Navigation(){return(<div className="navigation"><nav className="navbar navbar-expand-lg navbar-light bg-light"><div className="container-fluid"><a className="navbar-brand" href="#">Navbar</a><button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><span className="navbar-toggler-icon"></span></button><div className="collapse navbar-collapse" id="navbarNav"><ul className="navbar-nav"><li className="nav-item"><a className="nav-link active" aria-current="page" href="/">Home</a></li><li className="nav-item"><a className="nav-link" href="/dashboard">Dashboard</a></li></ul></div></div></nav></div>);}export default Navigation;

Now import our Navigation.jsx in our App.js file.

import React from "react"import Navigation from "./components/Navigation";function App() {return (<div className=""><Navigation /></div>);}exportdefault App;

Now you will be able to see your navigation bar on root route (React Routing)

Once you can see the navigation bar lets add another component called as Dashboard.jsx.

import React from "react";function Dashboard(){return(<div className="dashboard"><h1>This is Dashboard with /dashboard router</h1></div>);}export default Dashboard;

Now we will create another route called as Home that will be render on root route “/”.

import React from "react";function Home(){return(<div className="home"><h1>This is Home router rendered on "/"</h1></div>);}export default Home;

Now import both components on App.js

import React from "react"import Home from "./components/Home";import Navigation from "./components/Navigation";import Dashboard from "./components/Dashboard";function App() {return (<div className=""><Navigation /><Home /><Dashboard /></div>);}export default App;

Now your Root route will look like this since we have not added react router all content is rendering on root router “/”.

Now after adding react-router-dom in our App.js our program will look like this.

import React from "react"import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";import Home from "./components/Home";import Navigation from "./components/Navigation";import Dashboard from "./components/Dashboard";function App() {return (<div className=""><Navigation /><Router><Routes><Route  path="/" element={ <Home />} /><Route  path="/dashboard" element={ <Dashboard />} /></Routes></Router></div>);}export default App;

Here we are rendering “Home” component on “/” router, “Dashboard” component on “/dashboard”. You might notice that <Navigation /> is outside Router tag. It is because we want to render Navigation on all routes.

Home rout “/”
Dashboard route “/”

Now this is working smoothly till now. But what if we want to make a dynamic route?

Now I am defining a route in our App.js that will be Dynamic.

import React from "react"import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";import Home from "./components/Home";import Navigation from "./components/Navigation";import Dashboard from "./components/Dashboard";import Message from "./components/Message";function App() {return (<div className=""><Navigation /><Router><Routes><Route  path="/" element={ <Home />} /><Route  path="/dashboard" element={ <Dashboard />} /><Route  path="custom/:route_id" element={ <Message />} /></Routes></Router></div>);}export default App;

Now we will be adding another component called as message that will render custom messages using dynamic route.

import React from "react";function Message(){return(<div className="message"></div>);}export default Message;

Let us consider that one of the user go to this router “custom/Musab”, we should get the route and display it on the screen.

/custom/Musab
import React from "react";import { useParams } from "react-router-dom";function Message(props){let { route } = useParams();console.log(route)return(<div className="message"><h1>User Entered this route {route}</h1></div>);}export default Message;

Now since we have a working custom/dynamic link we can use it by several techniques.

For example we have a blog website and it have multiple post and our user want to see a post separately on a single page. We will using custom post route. It might look like this “/post/7056” and the base format of “/post/post-id”.

Now we know how we can use React routing we will be able to use in our websites.

If you like this tutorial please consider liking, following and subscribing to receive more articles like this.

Subscribe to Newsletter: Get an email whenever Musab Abbasi publishes. (medium.com)

--

--

Musab Abbasi
Musab Abbasi

Written by Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.

No responses yet