In a traditional multi-page application (MPA), clicking a link forces the browser to request a completely new HTML document from the server. React applications, however, are typically Single-Page Applications (SPAs), where the entire UI logic resides on the client side.
React Router is the industry-standard library that enables client-side navigation, allowing users to move between different views (components) instantly without a full page refresh, while still maintaining distinct URLs.
1. Installation
Since React Router is an external library, it must be added to your project dependencies.
- Open your Terminal (or Command Prompt) inside your project directory (
my-first-app). - Run the following command:
npm install react-router-dom
2. Core Concepts
React Router uses three main components to manage routing:
| Component | Purpose | Location |
BrowserRouter | The router that enables client-side routing. It should wrap your entire application. | Placed in the entry file (index.js). |
Routes & Route | The mapping that defines which component should render for a specific URL path. | Placed in the main component (App.js). |
Link | The navigation component used instead of the standard HTML <a href="..."> tag. | Placed in the component that holds your navigation bar. |
3. Setup and Configuration
The router must be set up at the highest level of your application.
A. index.js (Router Wrapper)
Open src/index.js and wrap the main <App /> component with BrowserRouter:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom'; // 1. Import the BrowserRouter
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
{/* 2. Wrap the entire App in the router */}
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
B. Navigation Components
Create three simple component files to serve as your different pages: Home.js, About.js, and Contact.js.
Example Home.js:
import React from 'react';
function Home() {
return <h1>Welcome Home!</h1>;
}
export default Home;
// (Create similar simple files for About.js and Contact.js)
4. Execution Example: Defining Routes and Navigation
In your my-first-app/src directory, open App.js and define your navigation bar and the route mapping.
import React from 'react';
// Import the necessary routing components
import { Routes, Route, Link } from 'react-router-dom';
// Import your page components
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<div className="AppRouter">
{/* 1. Navigation Bar (Always visible) */}
<nav style={{ padding: '10px', backgroundColor: '#f0f0f0' }}>
{/* Use the <Link> component for navigation */}
<Link to="/" style={{ margin: '10px' }}>Home</Link>
<Link to="/about" style={{ margin: '10px' }}>About</Link>
<Link to="/contact" style={{ margin: '10px' }}>Contact</Link>
</nav>
<hr />
{/* 2. Routes Wrapper */}
<div className="PageContent">
<Routes>
{/* 3. Define individual routes: Maps URL path to Component */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
{/* Optional: Catch-all route for 404 pages */}
<Route path="*" element={<h1>404: Page Not Found</h1>} />
</Routes>
</div>
</div>
);
}
export default App;
- Local Execution: Run
npm start. - Observation: Clicking the
<Link>components updates the URL in the address bar and instantly swaps the component rendered inside the<Routes>container, without reloading the entire page.
5. Route Parameters (Dynamic Routes)
To create dynamic routes (e.g., viewing details for a specific user ID), you use a colon (:) followed by the parameter name in the path.
Example Dynamic Route:
<Route path="/users/:userId" element={<UserProfile />} />
Inside the UserProfile component, you can retrieve the value of userId using the useParams hook:
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams(); // Retrieves the value from the URL path
return <h2>Viewing Profile for User ID: {userId}</h2>;
}
