What Is BrowserRouter in React

What Is BrowserRouter?

BrowserRouter is a powerful router component of the React Router DOM library that uses the HTML5 history API (pushState, replaceState, and popState) to handle navigation. It allows your React app to change the URL like /about /contact without refreshing the entire webpage.

  • pushState: Change the URL without reloading the whole page.
  • replaceState: Replace the current URL
  • popState: Delete when the user navigates using the back and forward buttons.

In React, the server has only one HTML page, index.html and all the other pages, like about, contact, are accessed through JavaScript. But when we manually search the about page URL in the browser, it will give us a 404 Not Found error.

In this case, Browser Router is the solution to change the URL without any problem. Here’s the solution to these problems according to different servers and platforms:

1) Netlify:

Follow these steps if you’re hosting your React app on Netlify:

  1. Create a “_redirects” file in the Root folder of your React project.
_redirects
  1. Add this line inside the file:
/*    /index.html   200

This tells Netlify to return the index.html file for any route.

2) Vercel

Vercel is a modern and smart hosting platform specially designed for Frontend frameworks (like React, Next.js, Vue, Svelte, etc.), Static websites and Serverless functions.

If you are using the Vercel platform, first create Vercel.json file in the root of your React project and then add this code:

{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}

It always renders the index.html file to prevent a 404 error on your webapp.

3) Express.js (Custom Node.js Server)

When we build a React app using “npm run build” command, it generates a production-ready version of our app inside a Build folder. This includes all the files such as index.html, JavaScript, CSS and static assets.

When we serve this app using a Express.js server, so make sure the static files (like CSS, JS, images) are served correctly and any unknown URL (like /about, /contact) is always redirected to the index.html file.

This process is essential because React Router handles routes on the client-side, and the server doesn’t know about them.

const express = require('express');
const path = require('path');
const app = express();

// Serve static files from the build folder
app.use(express.static(path.join(__dirname, 'build')));

// For all other routes, return index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(3000);

This code setup redirects all the static files to the index.html without any errors.

This setup are needed because React apps are Single Page Applications (SPA), so it’s depend on client-side routing.

How to Install BrowserRouter In React App

First, we need to install the react-router-dom package in our app. This is the official routing library for React applications.

Here’s the Installation command:

npm install react-router-dom

After installation, import BrowserRouter in your main application file:

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

Basic Example of Browser Routing

BrowserRouter wraps your entire app inside this component.

import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';

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

export default App;

In this example:

  • BrowserRouter enables the URL navigation
  • Routes is a container for multiple routes of our app.
  • Each Route matches a particular path to a route component.

Key Components of BrowserRouter

<Route>

The <Route> component matches a specific URL path and shows that component on the screen.

<Route path="/contact" element={<ContactPage />} />

<Link>

The <link> component enables internal navigation on your app without reloading a page.

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

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

useNavigate()

React-router-dom provides a useNavigate() hook, which allows you to navigate to another page using JavaScript without clicking a <link>.

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

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

const handleLogout = () => {
// logout logic
navigate('/login');
};

return <button onClick={handleLogout}>Logout</button>;
}

Book Review App Using BrowserRouter

Let’s, we are building a small app using BrowserRouter where students can:

  • View a list of books
  • Users can click on a book to see its review
  • Most important, navigate without reloading the page

Code:

// App.jsx
import React from 'react';
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';

const books = [
{ id: '1', title: 'React', review: 'Great for beginners to understand React.' },
{ id: '2', title: 'JavaScript', review: 'Covers all the JS topics clearly.' },
{ id: '3', title: 'Python', review: 'Perfect for students who are preparing for coding interviews.' }
];

// Home Page Component
function Home() {
return (
<div>
<h1>Welcome to Book Review Center</h1>
<p>This app helps students find quick reviews of popular programming books.</p>
<Link to="/books">Go to Book List</Link>
</div>
);
}

// Book List Component
function BookList() {
return (
<div>
<h2>Book List</h2>
<ul>
{books.map(book => (
<li key={book.id}>
<Link to={`/books/${book.id}`}>{book.title}</Link>
</li>
))}
</ul>
<Link to="/">Back to Home</Link>
</div>
);
}

// Book Review Component (Dynamic Route)
function BookReview() {
const { id } = useParams();
const book = books.find(book => book.id === id);

if (!book) {
return <h3>Book not found.</h3>;
}

return (
<div>
<h2>{book.title}</h2>
<p>{book.review}</p>
<Link to="/books">Back to Book List</Link>
</div>
);
}

// App Component with BrowserRouter
function App() {
return (
<BrowserRouter>
<nav style={{ padding: '10px', background: '#f0f0f0' }}>
<Link to="/" style={{ marginRight: '10px' }}>Home</Link>
<Link to="/books">Books</Link>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/books" element={<BookList />} />
<Route path="/books/:id" element={<BookReview />} />
</Routes>
</BrowserRouter>
);
}

export default App;

Code Explanation:

First, BrowserRouter wraps the whole app, then different routes are defined for different scenarios like:

  • / => Shows a welcome message to the screen.
  • /books => It lists all the available books.
  • /books/:id => Shows all reviews according to the book’s ID.

The <Link> tag is used to change pages without refreshing the whole webapp, and the useParams() function gets the dynamic ID from the URL to display the correct book review.

Leave a Comment