What Is React Router

React Router is a powerful routing library for React applications that allows developers to create dynamic, single-page applications (SPAs) with multiple views and pages.

React Router is a tool used in React applications to control what content is show based on the URL path, without refreshing the whole page.

Normally, when you click on a link in a website, the browser reloads the entire page. But with React Router:

  • Only the necessary parts of the page are updated.
  • The experience feels fast and smooth, like you’re staying on one page (this is called a Single Page Application or SPA).
  • It uses the browser’s history system (like forward/back buttons) to manage navigation.

React Router provides a “single-page application” experience by updating only certain webpage by manipulating the browser’s history API, for faster navigation and improved user experience.

Why Use React Router?

  • Single Page Application (SPA) Support: React Router allows navigation between pages without reloading the entire website.
  • Declarative Routing: You define routes like you write React components in a clear, structured, and readable way. This makes your code easy to manage and update.
  • Nested Routes: You can place routes inside other routes, which is useful when different parts of a page have their own navigation. For example, a dashboard with tabs like “Profile”, “Settings”, etc.
  • Dynamic Route Matching: You can create routes with variables (e.g., /user/:id). this means you can show different content for different URLs, like /user/101 or /user/205.
  • History Management: React Router controls the browser’s forward and back buttons, allowing users to navigate smoothly without losing track of their previous pages.

Installing and Setting Up React Router

To started with React Router, you need to install the library. React Router can be installed using npm or yarn:

npm install react-router-dom
# Or using yarn
yarn add react-router-dom

After installation, you can import the necessary components to set up routing in your application.

Key Components of React Router

React Router consists of several key components that enable navigation, define routes and manage views.

1. Browser Router

  • BrowserRouter is a component from React Router that wraps your entire app. It sets up routing so you can use <Route> and <Link> components to navigate between pages.
  • Uses the HTML5 history API for navigation.
import { BrowserRouter } from 'react-router-dom';

function App() {
return (
<BrowserRouter>
{/* Your routes go here */}
</BrowserRouter>
);
}

2. Routes and Route

  • Routes: This is a container component that holds all your <Route>. like a box that hold all the paths of your app.
  • Route: Hold only Each <Route> which to show in the webpage. like a certain path.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Homepage from './components/Homepage';
import AboutSection from './components/AboutSection';

function MyWebsiteApp() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Homepage />} />
<Route path="/about" element={<AboutSection />} />
</Routes>
</BrowserRouter>
);
}

export default MyWebsiteApp;

3. Link

  • The Link component replace HTML <a> tags for navigation. It allows navigation without reloading the page and improving performance.
import { Link } from 'react-router-dom';

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

4. Navigate

  • The <Navigate /> component in React Router is used to redirect users to another route without clicking on a link.
  • You use it when you want to automatically move the user to another page based on a condition like:
  • User is not logged in → redirect to login page
  • Form submitted successfully → redirect to a thank-you page
import { Navigate } from 'react-router-dom';

function PrivateRoute({ isAuthenticated }) {
return isAuthenticated ? <Dashboard /> : <Navigate to="/login" />;
}

5. use Params

  • use Params is a special React Router hook, you can get values directly from the URL path.
  • When your route contains dynamic segments like /user/:id or /profile/:username, useParams helps you read those dynamic values (e.g., id, username) inside the component.
import { useParams } from 'react-router-dom';

function UserProfile() {
const { userId } = useParams();
return <div>User ID: {userId}</div>;
}

Configuring Routes with React Router

React Router enables a structured approach to defining and managing different routes in an application. Here’s how to set up basic, nested, and dynamic routes:

Basic Routes

You use <BrowserRouter>, <Routes> and <Route> to map a URL path (like /about or /home) to a specific React component.

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

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

Nested Routes

Nested routes in React Router let you embed child routes inside a parent route, which is useful when multiple pages share a common layout or structure.

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

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard/*" element={<Dashboard />} />
</Routes>
</BrowserRouter>
);
}

Dynamic Routes

Dynamic routes contain variable parts, such as ID or username and allowing for more flexible URLs. The useParams hook helps retrieve parameters.

function UserDetails() {
const { userId } = useParams();
return <h2>User ID: {userId}</h2>;
}

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

In this example, visiting /user/123 would display User ID: 123.

Programmatic Navigation with useNavigate

The useNavigate hook enables navigation programmatically from within a function, which is useful for redirecting users after form submissions, login, or other events.

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

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

function handleLogin() {
// Assume login logic here
navigate('/dashboard');
}

return <button onClick={handleLogin}>Login</button>;
}

Here, calling navigate(‘/dashboard’) after login will redirect the user to the dashboard.

Example Project Structure with React Router

Consider a application with Home, About and Dashboard pages. The Dashboard has sub-routes for Profile and Settings:

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

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

This structure enables dynamic navigation, nested routes and keeps your application highly organized.

Leave a Comment

BoxofLearn