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>
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
Wrap Your App with BrowserRouter
function App() {
return (
<BrowserRouter>
{/* Your app content */}
</BrowserRouter>
);
}
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>
);
}
- BrowserRouter wraps your app and enables routing functionality
- Link components create navigation links
- Routes and Route define your routing configuration
References
Top comments (2)
The definitions and examples are very clear and easy to understand.
Thank you🤩.
Thank you😍