Single page application


Routing with React Router
React Router is a standard library for routing in React. It is used to develop Single Page Applications (SPAs) by enabling navigation among different views of components, changing the browser URL, and keeping the user interface (UI) in sync with the URL.




5.9 Routing with React Router

Routing is a technique by which the user is directed to different pages based on their action. In ReactJS, routing is mainly used to develop Single Page Applications (SPAs). A single page application dynamically rewrites the current page instead of loading new pages from the server.

When a user types a specific URL in the browser, if this URL path matches any route defined in the router file, the user is redirected to that component or page. Popular sites like YouTube, Facebook, and Instagram use ReactJS routing for rendering multiple views.

React Router Packages

Two important packages are used:

  1. react-router – Provides core routing components and functions.
  2. react-router-dom – Enables dynamic routing in web applications.

React Router is the core package, while React Router DOM contains DOM bindings and gives default access to React Router.

React Router API Elements

  • → Keeps the UI in sync with the URL.
  • → Renders a navigation link.
  • → Renders UI component depending on the URL.
  • → Handles dynamic URL routing.

Demo Example

Step 1: Create a new React project

D:\reactDemo> create-react-app routerdemo

Step 2: Install React Router package

npm install react-router-dom

Step 3: Create welcome.js inside src

import React from 'react';
function Welcome() {
  return (
    <div>
      <h1>Welcome User!!!!</h1>
    </div>
  );
}
export default Welcome;

Step 4: Create contact.js inside src

import React from 'react';
function Contact() {
  return (
    <div>
      <p><b>Phone:</b> 1234567890</p>
      <p><b>Email:</b> abc.xyz@gmail.com</p>
    </div>
  );
}
export default Contact;

Step 5: Modify index.js to define routes

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Routes, Route } from 'react-router-dom';
import Welcome from './welcome';
import Contact from './contact';

function App() {
  return (
    <div>
      <h1>Router Demo</h1>
      <ul>
        <li><Link to="/welcomepg">Welcome Page</Link></li>
        <li><Link to="/contactpg">Contact Page</Link></li>
      </ul>
      <Routes>
        <Route path="/welcomepg" element={<Welcome />} />
        <Route path="/contactpg" element={<Contact />} />
      </Routes>
    </div>
  );
}

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

Step 6: Run the application

npm start
  • Clicking Welcome Page → Displays “Welcome User!!!”
  • Clicking Contact Page → Displays Phone and Email.

Types of Routers in React

React Router provides three types of routers:

  1. Memory Router

    • Stores history in memory (not in browser).
    • Does not update browser address bar.
    • Useful for testing and React Native.
    import { MemoryRouter as Router, Route, Link, Switch } from 'react-router-dom';
    
  2. Hash Router

    • Uses the hash (#) part of the URL (window.location.hash).
    • Server ignores hash value; always serves index.html.
    • Useful for legacy browsers or when no server-side route handling is present.
    • Not recommended by React Router team.
    import { HashRouter as Router } from 'react-router-dom';
    
  3. Browser Router

    • Uses HTML5 History API (pushState, replaceState, popState).
    • Routes behave as normal browser URLs (/about, /contact).
    • Assumes server handles all requests.
    • Supports forceRefresh for old browsers.
    import { BrowserRouter, Routes, Route } from 'react-router-dom';
    

Folder Structure Example with Browser Router

Inside src/pages/:

  • Layout.js
  • Home.js
  • Blogs.js
  • Contact.js
  • NoPage.js
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="blogs" element={<Blogs />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Installation Summary

  • Install → npm i react-router-dom
  • Import → import { BrowserRouter, Routes, Route } from 'react-router-dom';

Final Definition:
React Router is a standard routing library in React used to build Single Page Applications. It enables navigation between different views, updates the browser URL, and keeps the UI in sync with the URL.