Introduction & concepts in React Router

React Masters
4 min readJun 28, 2024

--

React Routers

React Router is an essential library for any React developer looking to create dynamic, single-page applications with seamless navigation. This guide dives deep into React Router, offering detailed insights, examples, and best practices to help you master this powerful tool.

Introduction to React Router

React Router is a collection of navigational components that compose declaratively with your application. Whether you’re building a simple single-page application or a complex multi-page one, React Router helps manage the navigation and URLs in your application.

Setting Up React Router

Before implementing, you must set up a React Router in your React project. Follow these steps:

Step 1: Install React Router

First, install the React Router package via npm:

npm install react-router-dom

Step 2: Importing BrowserRouter

Next, wrap your application in a BrowserRouter component. This component keeps your UI in sync with the URL.

import { BrowserRouter } from 'react-router-dom';

function App() {
return (
<BrowserRouter>
<YourComponent />
</BrowserRouter>
);
}

export default App;

Defining Routes

Routes are the foundation of React Router. They define the paths in your application and the components that should render when the URL matches those paths.

Basic Route Setup

Here’s how to set up basic routes in your application:

import { Route, Routes } from 'react-router-dom';

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}

function Home() {
return <h1>Home Page</h1>;
}

function About() {
return <h1>About Page</h1>;
}

function Contact() {
return <h1>Contact Page</h1>;
}

Nested Routes

Nested routes allow you to render components inside other components. This is particularly useful for dashboards and other complex layouts.

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Routes>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Routes>
</div>
);
}

function Profile() {
return <h1>Profile Page</h1>;
}

function Settings() {
return <h1>Settings Page</h1>;
}

Dynamic Routing

Dynamic routing allows you to pass parameters through the URL. This is useful for creating routes that depend on data, such as user profiles or product pages.

Route Parameters

You can define dynamic segments of the URL by using a colon (:) in the route path.

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/user/:id" element={<User />} />
</Routes>
</BrowserRouter>
);
}

function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}

Using useParams

The useParams hook is used to access the parameters defined in the route path.

import { useParams } from 'react-router-dom';

function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}

Navigation

Navigation in React Router can be handled using the Link component or the useNavigate hook.

Using Link

The Link component creates navigational links that allow users to move around the application.

import { Link } from 'react-router-dom';

function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}

Programmatic Navigation

The useNavigate hook allows you to navigate programmatically in your application.

import { useNavigate } from 'react-router-dom';

function Home() {
const navigate = useNavigate();

const goToAbout = () => {
navigate('/about');
};

return (
<div>
<h1>Home Page</h1>
<button onClick={goToAbout}>Go to About</button>
</div>
);
}

Protected Routes

Protected routes are essential for applications that require authentication. They restrict access to certain parts of the application based on user authentication status.

Creating a Protected Route

You can create a higher-order component to wrap protected routes.

import { Navigate } from 'react-router-dom';

function ProtectedRoute({ element, isAuthenticated }) {
return isAuthenticated ? element : <Navigate to="/login" />;
}

function App() {
const isAuthenticated = false; // Replace with actual authentication logic

return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/dashboard" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Dashboard />} />} />
</Routes>
</BrowserRouter>
);
}

Handling 404 Pages

A common requirement is to handle 404 pages when no routes match the URL.

Setting Up a 404 Route

You can set up a catch-all route that renders a 404 component.

function NotFound() {
return <h1>404 Not Found</h1>;
}

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}

Diagram: React Router Flow

Here’s a diagram to illustrate the flow of a basic React Router setup:

graph LR
A[BrowserRouter] --> B[Routes]
B --> C[Route path="/"]
B --> D[Route path="/about"]
B --> E[Route path="/contact"]
B --> F[Route path="*"]
C --> G[Home]
D --> H[About]
E --> I[Contact]
F --> J[NotFound]

Conclusion

React Router is a versatile and powerful library for managing navigation in React applications. By understanding and utilizing its various features — such as route definitions, dynamic routing, nested routes, and protected routes — you can create a seamless and intuitive user experience in your applications. Keep experimenting and exploring to make the most out of React Router.

Hope you like the article about the react-router topic for more details regarding the React JS Course or the free demo sessions Contact us at Mob: +91 84660 44555

--

--