React Router is a library used in React to manage client-side routing by mapping URL paths to components without reloading the page.
Client-Side Routing: Enables navigation without full page reloads.
URL Mapping: Connects URL paths to specific components.
Dynamic Navigation: Allows seamless switching between views.
Improved Performance: Updates only required components instead of the whole page.
Let us install the React Router package:
npm install react-router
Components
Here are the main components used in React Router:
- BrowserRouter and HashRouter
BrowserRouter: Uses the HTML5 history API to keep your UI in sync with the URL.
HashRouter: Uses the hash portion of the URL (i.e., window.location.hash) to keep your UI in sync with the URL.
<BrowserRouter>
{/* Your routes go here */}
</BrowserRouter>
2. Routes and Route
Routes: A container for all your route definitions.
Route: Defines a single route with a path and the component to render.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
3. Link and NavLink
Link: Creates navigational links in your application.
NavLink: Similar to Link but provides additional styling attributes when the link is active.
<NavLink
to="/"
className={({ isActive }) => (isActive ? "active" : "")}
>
Home
</NavLink>
Top comments (0)