DEV Community

Cover image for React Router
Karthick (k)
Karthick (k)

Posted on

React Router

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
Enter fullscreen mode Exit fullscreen mode

Components
Here are the main components used in React Router:

  1. 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)