Mastering Navigation with React Router DOM: Beginner To Advance

CodeGenitor
4 min readApr 28, 2024

--

image captured of react-router-dom

Introduction:

React Router DOM is a crucial library for seamless navigation in React apps. In this post, we’ll explore its fundamentals and importance. Expect to learn about routes, links, and setup processes, empowering you to create dynamic single-page experiences effortlessly. Let’s dive into mastering navigation with React Router DOM!

Overview:

At the core of React Router DOM are several key concepts:

  1. Routes: in React Router DOM map URLs to React components, allowing developers to control which component renders based on the URL. This enables SPA experiences where content updates dynamically without page refreshes.
  2. Links: Links enable seamless navigation between pages/views in React. Implemented as <a> elements with a to attribute, they trigger React Router DOM to render the corresponding component, updating the URL.
  3. Parameters: Parameters in React Router DOM pass dynamic data to routes. Route parameters match parts of the URL, enabling dynamic routing. Query parameters, like key-value pairs in the URL, pass extra information between components or pages.

Installation and Setup:

Installing React Router DOM is straightforward. First, ensure you have a React project set up.

if you don't have a react project, you can fork the previous project from GitHub or follow the previous tutorial here.

Install React Router DOM using npm or yarn:

npm install react-router-dom

or

yarn add react-router-dom

Note:
Before running the installation commands for React Router DOM, make sure you’re in the frontend directory of your React project. This ensures that the package is installed within the correct location and integrated seamlessly into your project’s dependencies. You can also check react-router-dom documentation here

Setting Up Basic Routing:

  1. Inside the frontend directory of your project, navigate to the src directory. Create a folder named “routes”. Inside this folder, add a file called “index.route.tsx” to define your routes.
mkdir routes; cd routes; touch index.route.tsx

Note:
To execute the provided command, ensure you’re within the src directory of your project’s frontend in your terminal. You can also manually create the folder and file if needed.

2. Open the index.route.tsx file add the following code to implement a basic route:

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Homepage from "../pages/home/Homepage";
import Register from "../pages/register/Register";
import Login from "../pages/login/Login";

const AppRoutes = () => {


return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Homepage />} />
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
};

export default AppRoutes;

Note:
To remain current with the latest updates, it’s advisable to upgrade to React Router DOM version 6.23.0, ensuring compatibility with recent enhancements and optimizations

3. Now update the entry file called App.tsx with the route component as demonstrated below:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import AppRoutes from "./routes/index.route";

const App = () => {
return (
<div className="container">
<AppRoutes />
</div>
);
};

export default App;

Note:
Once you have updated it, you should see the home page of your application, and you can click on register and login to navigate, respectively.

4. Inside the pages folder, create a new folder namedhome. Within this folder, add a file called Homepage.tsx and write the following code as demonstrated below:

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

const Homepage = () => {
return (
<div className="container">
<h1>Homepage</h1>
<p>Welcome to the homepage of the application!</p>
<NavLink to="/register">
<button className="btn mx-3 btn-primary">Register</button>
</NavLink>
<NavLink to="/login">
<button className="btn btn-primary">Login</button>
</NavLink>
</div>
);
};

export default Homepage;

Note:
We utilized NavLink from React Router DOM to facilitate navigation, thus preventing the page from reloading, unlike with anchor tags.

Implement Navigation Guards:

Let’s implement protected routing for the application. If the user is logged in, they can view the homepage; otherwise, they will be directed to the register/login page.

Open the index.route.tsx file and update the code with the following:

import React from "react";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import Homepage from "../pages/home/Homepage";
import Register from "../pages/register/Register";
import Login from "../pages/login/Login";

// Component for defining application routes
const AppRoutes = () => {
// Check if user is authenticated (dummy value for demonstration)
const user = true;

return (
// Wrap routes with BrowserRouter to enable routing
<BrowserRouter>
{/* Define application routes */}
<Routes>
{/* Route for homepage, redirects to homepage if user is authenticated, otherwise redirects to login */}
{user ? (
<Route path="/" element={<Homepage />} />
) : (
<Route path="/" element={<Navigate to="/login" />} />
)}
{/* Route for registration page, redirects to homepage if user is authenticated, otherwise renders registration page */}
{user ? (
<Route path="/register" element={<Navigate to="/" />} />
) : (
<Route path="/register" element={<Register />} />
)}
{/* Route for login page, redirects to homepage if user is authenticated, otherwise renders login page */}
{user ? (
<Route path="/login" element={<Navigate to="/" />} />
) : (
<Route path="/login" element={<Login />} />
)}
{/* Route for 404 not found page, renders 404 not found page if no route matche*/}
<Route path="*" element={<h1>404 not found</h1>} />
</Routes>
</BrowserRouter>
);
};

export default AppRoutes;

🔒 In Conclusion: A Secure Future for Your Application

With the implementation of route protection, your application’s security has taken a significant step forward. Users can now navigate your platform with confidence, knowing their data is safeguarded.

🌟 What’s Next?

But our journey doesn’t end here! In our next tutorial, we’ll explore dynamic route protection, empowering you to adapt and refine access controls as your application evolves.

🚀 Stay Connected
Don’t miss out on the latest updates and tutorials! Subscribe to my blog and let’s be friends on Instagram, Facebook, and YouTube as CodeGenitor for exclusive content and exciting insights.

--

--

CodeGenitor
CodeGenitor

Written by CodeGenitor

Software developer passionate about coding, innovation, and tech trends. Turning ideas into reality, one line of code at a time.