DEV Community

Ezhil Abinaya K
Ezhil Abinaya K

Posted on

BrowserRouter in React

BrowserRouter
BrowserRouter is a component provided by React Router to enable client-side routing using the HTML5 history API, allowing navigation without full page reloads. It also updates the browser URL dynamically while preserving the application state during view changes.
Syntax

<BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
</BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

Install React Router
In the command line, navigate to your project directory and run the following command to install the package:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Wrap Your App with BrowserRouter

function App() {
  return (
    <BrowserRouter>
      {/* Your app content */}
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode

Basic Routing
React Router uses three main components for basic routing:

  • Link: Creates navigation links that update the URL
  • Routes: A container for all your route definitions
  • Route: Defines a mapping between a URL path and a component
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

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>
      {/* Navigation */}
      <nav>
        <Link to="/">Home</Link> |{" "}
        <Link to="/about">About</Link> |{" "}
        <Link to="/contact">Contact</Link>
      </nav>

      {/* Routes */}
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • BrowserRouter wraps your app and enables routing functionality
  • Link components create navigation links
  • Routes and Route define your routing configuration

References

Top comments (2)

Collapse
 
vigneshwaran_v profile image
Vigneshwaran V

The definitions and examples are very clear and easy to understand.
Thank you🤩.

Collapse
 
ezhil_abinayak_e38eec8fb profile image
Ezhil Abinaya K

Thank you😍