Popular Searches
Popular Course Categories
Popular Courses

Setting Up BrowserRouter

Setting Up BrowserRouter

React Router

Setting Up BrowserRouter in React

Topic: React JS Routing | Level: Beginner to Intermediate

1. Introduction to BrowserRouter

BrowserRouter is a routing component provided by React Router. It allows a React application to display different components based on the URL in the browser. It uses the browser's History API to handle client-side navigation without requiring a full page reload for each route change.

For example, a React application can have different pages such as Home, About, Services, Contact, and Login. Instead of creating a separate HTML page for each section, React Router displays the appropriate component according to the current URL.

Example URLs

  • http://localhost:5173/ — Home page
  • http://localhost:5173/about — About page
  • http://localhost:5173/services — Services page
  • http://localhost:5173/contact — Contact page

2. What Is React Router?

React Router is a library that manages navigation and route matching in React applications. It helps developers build Single Page Applications (SPAs) with multiple URL paths.

Important React Router Components

Component Purpose
BrowserRouter Provides browser-based routing context to the application.
Routes Groups route definitions and selects the matching route.
Route Maps a URL path to the component that should be displayed.
Link Provides navigation between routes without a full page reload.
NavLink Provides navigation links that can indicate the active route.
Navigate Redirects users to another route.

3. Why Do We Need BrowserRouter?

React applications often need multiple pages or views. Without a routing library, developers may need to manage URL changes and conditional rendering manually. BrowserRouter provides the routing context required by React Router's navigation and route-matching components.

  • Supports clean URLs such as /about and /contact.
  • Enables client-side navigation between components.
  • Works with the browser's Back and Forward buttons.
  • Helps organize large applications into separate route-based views.
  • Supports nested routing when combined with other React Router components.

4. Installing React Router

Before using BrowserRouter, install the React Router package in your React project.

Step 1: Open Your Project

Open your React project in VS Code or another code editor.

Step 2: Open the Terminal

Run the following command in your project directory:

npm install react-router

Note: Modern React Router versions use the react-router package for declarative routing APIs. Older React Router v6 projects commonly use react-router-dom. Follow the package and import instructions for the version already used by your project.

Step 3: Start the Development Server

npm run dev

If you are using a Vite-based project, the command starts the local development server.

5. Understanding BrowserRouter Syntax

BrowserRouter wraps the part of the React application that needs routing. Its child components can then use route definitions and navigation components.

import { BrowserRouter } from "react-router";

function App() {
  return (
    <BrowserRouter>
      {/* Place your routed application here */}
    </BrowserRouter>
  );
}

export default App;

In an existing React Router v6 project that uses react-router-dom, the equivalent import is commonly:

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

6. Setting Up BrowserRouter Step by Step

Step 1: Create the Page Components

Create separate components for the pages that your application will display.

Home.jsx

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

export default Home;

About.jsx

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

export default About;

Contact.jsx

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

export default Contact;

Step 2: Configure the Routes

Import BrowserRouter, Routes, and Route. Wrap the route definitions in BrowserRouter and associate each URL path with a component.

The following example uses the modern react-router import:

import { BrowserRouter, Routes, Route } from "react-router";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";

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

export default App;

For a React Router v6 project using react-router-dom, change the import line to:

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

Step 3: Run and Test the Application

Start the development server and open the local URL in your browser. Test the following paths:

  • / displays the Home component.
  • /about displays the About component.
  • /contact displays the Contact component.

7. Understanding Routes and Route Matching

The Routes component examines the current URL and selects the best matching route. Each Route defines a path and the React element to render when that path matches.

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/services" element={<Services />} />
</Routes>

In this example, visiting / displays Home, while visiting /services displays Services.

8. Adding Navigation with Link

BrowserRouter establishes the routing context, but users also need a way to navigate between pages. React Router's Link component provides client-side navigation without the full-page reload normally caused by a standard anchor navigation.

import { Link } from "react-router";

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

export default Navbar;

For React Router v6 projects using react-router-dom, import Link from that package instead.

9. Complete Example: BrowserRouter with Navigation

The following example combines BrowserRouter, Routes, Route, and Link in one file. It uses the modern react-router package.

import {
  BrowserRouter,
  Routes,
  Route,
  Link
} from "react-router";

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

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

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

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        {" | "}
        <Link to="/about">About</Link>
        {" | "}
        <Link to="/contact">Contact</Link>
      </nav>

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

export default App;

10. Where Should BrowserRouter Be Placed?

BrowserRouter is generally placed near the top of the application tree so all routed components can access the same router context.

Example using main.jsx:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import App from "./App";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);

If BrowserRouter is configured in main.jsx, do not wrap the same application in another BrowserRouter inside App.jsx. Use one router provider for that application tree.

With this setup, define only the routes and page components in App.jsx:

import { Routes, Route } from "react-router";
import Home from "./Home";
import About from "./About";

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

export default App;

11. Understanding the basename Property

The basename property configures a common base path for an application that is hosted inside a subdirectory.

<BrowserRouter basename="/app">
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</BrowserRouter>

With this configuration, the Home route is accessed at /app/ and the About route at /app/about. The hosting server must also be configured to serve the application correctly from that base path.

12. BrowserRouter vs. HashRouter

Feature BrowserRouter HashRouter
URL format /about /#/about
URL handling Uses the browser History API. Uses the URL hash.
Server configuration Direct route requests usually require a fallback to the SPA entry point. Often avoids server-side path fallback requirements because the hash is not sent as part of the HTTP request path.
Typical use Applications that need clean URLs. Deployments where server routing configuration is difficult or unavailable.

13. Common Errors and Solutions

Error Possible Cause Solution
Cannot resolve React Router import The package is not installed or the import path is incorrect. Install the correct package and check the version-specific import.
Router nested inside another router BrowserRouter has been added in multiple places. Keep a single top-level router for the application tree.
Routes do not display URL path or route element is incorrect. Check the path, component import, and console errors.
Direct URL refresh returns 404 The production server does not fall back to the SPA entry point. Configure the host to serve the React application's entry HTML for client-side routes.
Link causes unexpected full-page navigation A normal anchor or incorrect URL is being used. Use React Router's Link for internal route navigation.
Hooks report missing router context A component using a routing hook is rendered outside a router. Render that component within BrowserRouter or the appropriate router provider.

14. Best Practices for BrowserRouter

  • Place the router high enough in the component tree to provide context to all routed pages.
  • Use Link or NavLink for internal navigation.
  • Keep route definitions readable and organized as the application grows.
  • Use a clear fallback or not-found route for unknown URLs.
  • Check server configuration before deploying a BrowserRouter application.
  • Use consistent import paths that match the installed React Router version.
  • Avoid wrapping the same application tree in multiple BrowserRouter components.

15. Practical Exercise: Create a Multi-Page React App

Objective: Build a simple website with Home, About, Services, and Contact pages.

Requirements

  1. Install React Router in your React project.
  2. Create four page components.
  3. Wrap the application with BrowserRouter.
  4. Define all four routes using Routes and Route.
  5. Add a navigation bar using Link.
  6. Test navigation using the browser's Back and Forward buttons.
  7. Refresh a nested URL and verify the server fallback configuration when testing a deployed build.

Expected Result

Each navigation link should display its matching page while keeping the React application running. The URL should update to match the selected route.

16. Interview Questions and Answers

Q1. What is BrowserRouter in React?

Answer: BrowserRouter is a React Router component that enables browser-based client-side routing using the browser History API.

Q2. Why do we use BrowserRouter?

Answer: It provides routing context so the application can match URLs to components and navigate between views.

Q3. What is the difference between BrowserRouter and Route?

Answer: BrowserRouter provides the router context, while Route defines which component should render for a matching path.

Q4. What is the purpose of Routes?

Answer: Routes groups route definitions and renders the best matching route for the current location.

Q5. Does BrowserRouter reload the whole page for every Link click?

Answer: No. React Router's Link normally performs client-side navigation without a full-page reload.

Q6. Why might refreshing a nested URL return a 404 error?

Answer: The web server may not be configured to serve the SPA entry HTML for that route. The server or hosting platform needs an appropriate fallback configuration.

Q7. Can an application have multiple BrowserRouter components?

Answer: Avoid nesting multiple BrowserRouter components around the same application tree. Use one router provider for that tree.

17. Quick Revision Checklist

  • Understand the purpose of BrowserRouter.
  • Install the appropriate React Router package.
  • Import BrowserRouter, Routes, and Route from the correct package.
  • Wrap the routed application in BrowserRouter.
  • Map URL paths to components with Route.
  • Use Link for client-side navigation.
  • Test URLs, Back/Forward navigation, and page refreshes.
  • Configure SPA fallback behavior on the production server.

18. Official Documentation

19. React JS Training and Course Demo

Learn more about React JS concepts, routing, reusable components, and building modern web applications through the following resources:

20. Conclusion

BrowserRouter is a key part of browser-based routing in React applications. It provides routing context and works with Routes, Route, and Link to create a multi-page experience within a Single Page Application. Correct setup, consistent package imports, and suitable production server configuration help ensure that navigation works reliably.

Previous Next
whatsapp