Introduction to React Router

What is React Router?

React Router is a JavaScript library that allows React applications to handle navigation without reloading the page. It enables client-side routing, making your app behave more like a multi-page website while still being a Single Page Application (SPA).

Installing React Router

To use React Router, we need the react-router-dom package. This package includes everything needed for routing in web-based React applications.
When using npm install react-router-dom, you need to run the command inside your project folder.

Create a Basic React Router Setup

This React code sets up a basic routing system using React Router. It allows navigation between a Home Page ("/") and an About Page ("/about").
        
            // Import necessary components from react-router-dom for routing
            import { BrowserRouter, Routes, Route } from "react-router-dom";

            // Define the Home component that will be shown when the user visits "/"
            function Home() {
              return <h1>Home Page</h1>; // Displays a heading "Home Page"
            }

            // Define the About component that will be shown when the user visits "/about"
            function About() {
              return <h1>About Page</h1>; // Displays a heading "About Page"
            }

            // Define the main App component
            function App() {
              return (
                // BrowserRouter is the parent component that enables React Router
                <BrowserRouter>
                  {/* Routes is a wrapper for multiple Route components */}
                  <Routes>
                    {/* Route for the Home page: "/" means the root URL (e.g., http://localhost:3000/) */}
                    <Route path="/" element={<Home />} />
                    {/* Route for the About page: "/about" (e.g., http://localhost:3000/about) */}
                    <Route path="/about" element={<About />} />
                  </Routes>
                </BrowserRouter>
              );
            }
            // Export the App component so it can be used in index.js
            export default App;
        
    

What Happens in the Browser?

URL Entered Component Displayed
http://localhost:3000/ Home Page
http://localhost:3000/about About Page

Explanation of Each Part

Adding Navigation Links

In the above example, users must type URLs manually. Let's add clickable navigation.

Step 1: Create a Header.js Component

    
        import { Link } from "react-router-dom";
        
        function Header() {
          return (
            <header>
              <h1>My Website</h1>
              <nav>
                <Link to="/">Home</Link> | 
                <Link to="/about">About</Link>
              </nav>
            </header>
          );
        }
        
        export default Header;
    

Step 2: Use Header.js in App.js

    
            import { BrowserRouter, Routes, Route } from "react-router-dom";
            import Header from "./Header";
        
            function Home() {
              return <h1>Home Page</h1>; // Displays a heading "Home Page"
            }

            function About() {
              return <h1>About Page</h1>; // Displays a heading "About Page"
            }

            function App() {
              return (      
                <BrowserRouter>
                 <Header />  {/* Display navigation links */}
                  <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" element={<About />} />
                  </Routes>
                </BrowserRouter>
              );
            }
        
            export default App;
        
    

How It Works

Handling 404 Pages (Not Found)

If a user enters an unknown URL, display a 404 error page.

Building a Stylish Navigation Bar with React Router

Step 1: Create Navbar.js

Inside your src folder, create a new file called Navbar.js:
    
        import { Link } from "react-router-dom";
        import "./Navbar.css"; // Import CSS for styling
        
        function Navbar() {
          return (
            <nav className="navbar">
              <div className="logo">MyWebsite</div>
              <ul className="nav-links">
                <li>
                  <Link to="/">Home</Link>
                </li>
                <li>
                  <Link to="/about">About</Link>
                </li>
                <li>
                  <Link to="/contact">Contact</Link>
                </li>
              </ul>
            </nav>
          );
        }
        
        export default Navbar;
    

Step 2: Create Navbar.css

Inside src, create a new file called Navbar.css:
    
        /* Navbar container */
        .navbar {
          display: flex;
          justify-content: space-between;
          align-items: center;
          background-color: #333;
          padding: 15px 20px;
        }
        
        /* Website logo */
        .logo {
          font-size: 24px;
          font-weight: bold;
          color: #fff;
        }
        
        /* Navigation links */
        .nav-links {
          list-style: none;
          display: flex;
          gap: 20px;
        }
        
        .nav-links li {
          display: inline;
        }
        
        /* Link styles */
        .nav-links a {
          text-decoration: none;
          color: #fff;
          font-size: 18px;
          padding: 8px 12px;
          border-radius: 5px;
        }
        
        .nav-links a:hover {
          background-color: #ff6b6b;
          color: #fff;
        }
    

Use Navbar in App.js

Now, modify your App.js file to include the Navbar component:
    
        import { BrowserRouter, Routes, Route } from "react-router-dom";
        import Navbar from "./Navbar"; // Import the Navbar
        
        function Home() {
          return <h1>Home Page</h1>;
        }
        
        function About() {
          return <h1>About Page</h1>;
        }
        
        function Contact() {
          return <h1>Contact Page</h1>;
        }
        
        function App() {
          return (
            <BrowserRouter>
              <Navbar /> {/* Add Navbar at the top */}
              <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                <Route path="/contact" element={<Contact />} />
                <Route path="*" element={<h1>404 - Page Not Found</h1>} />
              </Routes>
            </BrowserRouter>
          );
        }
        
        export default App;
    

Organizing Components: Separating Pages in React Router

Separating the Home, About, and Contact components into their own files will keep your project organized and maintainable. Here's how you can do it:

Step 1: Create Separate Component Files

Step 2: Update App.js

Now, modify your App.js file to import and use these separate components:
    
        import { BrowserRouter, Routes, Route } from "react-router-dom";
        import Navbar from "./Navbar"; // Import the Navbar
        import Home from "./Home"; // Import Home component
        import About from "./About"; // Import About component
        import Contact from "./Contact"; // Import Contact component
        
        function App() {
          return (
            <BrowserRouter>
              <Navbar /> {/* Add Navbar at the top */}
              <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                <Route path="/contact" element={<Contact />} />
                <Route path="*" element={<h1>404 - Page Not Found</h1>} />
              </Routes>
            </BrowserRouter>
          );
        }
        
        export default App;
    

Traditional Websites vs React Router

Feature Traditional Websites (Server-Side Routing) React Router (Client-Side Routing)
How pages load Each page request loads a new HTML file from the server. Only one HTML file (`index.html`) is loaded initially.
Navigation Clicking a link sends a request to the server, which responds with a new page. Clicking a link updates the URL and renders a new component without a page reload.
Performance Slower because each navigation requires a full page reload. Faster because only the necessary parts of the page update.
Example Behavior
  • Visiting `/` loads `index.html`.
  • Clicking "About" requests `about.html`.
  • The browser refreshes to load `about.html`.
  • Visiting `/` loads `index.html` once.
  • Clicking "About" does not reload—React dynamically replaces content.