How to Implement BrowserRouter in React

This article provides a straightforward, step-by-step guide on how to implement BrowserRouter in a React application. You will learn how to install the necessary routing package, wrap your application root, configure your navigation routes, and enable seamless client-side page transitions without reloading the browser.

Step 1: Install react-router-dom

To use BrowserRouter, you must first install the react-router-dom library, which is the standard routing package for React web applications. Run the following command in your project’s terminal:

npm install react-router-dom

Step 2: Wrap Your App with BrowserRouter

To enable routing across your entire application, you need to wrap your root component with BrowserRouter. Open your entry point file (usually main.jsx, index.js, or index.tsx) and import the component from the library.

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

Step 3: Define Your Routes and Navigation

With the BrowserRouter context configured, you can now define specific URL paths and map them to different components. You will use the Routes and Route components to define your paths, and the Link component to handle navigation.

Here is an example of how to set this up in your App.js or App.jsx file:

import { Routes, Route, Link } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

function App() {
  return (
    <div>
      {/* Navigation Menu */}
      <nav style={{ padding: '10px', background: '#f0f0f0' }}>
        <Link to="/" style={{ marginRight: '10px' }}>Home</Link>
        <Link to="/about" style={{ marginRight: '10px' }}>About</Link>
        <Link to="/contact">Contact</Link>
      </nav>

      {/* Route Configuration */}
      <main style={{ padding: '20px' }}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </main>
    </div>
  );
}

export default App;

Key Components Explained