How to Implement React Router in React
This article provides a step-by-step guide on how to implement React Router in a React application. You will learn how to install the package, configure the routing environment, define your application routes, and enable seamless client-side navigation between different pages.
Step 1: Install React Router DOM
To get started, you need to install the react-router-dom
library, which contains the DOM bindings for React Router. Run the
following command in your project terminal:
npm install react-router-domStep 2: Configure the Router
To enable routing throughout your application, you must wrap your
root component with BrowserRouter. Open your main entry
file (typically main.jsx or index.js) and
import BrowserRouter.
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
Once the router is configured, you can define your application
routes. In your App.js or App.jsx file, import
Routes and Route from
react-router-dom, along with the components you want to
render for each page.
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
}
export default App;Routesacts as a container for all your individualRoutedefinitions.Routetakes apathprop (the URL path) and anelementprop (the React component to render when the path is matched).
Step 4: Implement Navigation Links
To navigate between pages without triggering a full browser reload,
use the Link component instead of standard HTML anchor
(<a>) tags.
import { Link, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<div className="App">
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
}
export default App;Using the to attribute in the Link
component ensures that React Router intercepts the click event and
updates the view dynamically, preserving the single-page application
experience.