When creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.
React Router
React Router is a declarative, component-based routing library for React applications. It enables navigation without reloading the page, making the application faster and more dynamic.
- Supports client-side routing in React applications.
- Provides nested routes for better organization.
- Allows for dynamic routing using parameters.
- Enables programmatic navigation via hooks like
useNavigate().
Before diving into types of routers, let’s ensure that React Router DOM is installed in your React project
npm install react-router-domTypes of Routers in React
React provides several types of routers that serve different purposes. The main routers in React are
- Browser Router (<BrowserRouter>)
- Hash Router (<HashRouter>)
- Memory Router (<MemoryRouter>)
- Static Router (<StaticRouter>)
- Native Router (<NativeRouter>)
1. Browser Router
BrowserRouter is the most commonly used router in React applications that are deployed in a modern web environment.
- It uses the HTML5 history API to manage the navigation.
- This router makes use of pushState, replaceState, and the popState event to keep the UI in sync with the URL.
- It allows for clean and human-readable URLs without hash fragments.
Usage of BrowserRouter
BrowserRouter is a powerful and commonly used router in React applications, and it’s ideal for web applications that require clean, SEO-friendly URLs and rely on server-side routing.
- Hosting on a Web Server with Proper Routing: BrowserRouter works best when your app is hosted on a web server that can handle dynamic URLs (server-side routing).
- Improved SEO: Since BrowserRouter generates URLs without the hash, search engines can more easily crawl and index your pages.
- Single Page Applications (SPA): BrowserRouter is commonly used in SPAs, where the entire app runs on a single page.
- Handling Multiple Views or Pages: If your app includes multiple views or pages BrowserRouter helps manage these views by linking each one to a specific URL.
import React from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";