Understanding React Router: Building Multi-Page Applications in React
Modern web applications often require multiple pages such as Home, About, Contact, and Projects. In React, we can achieve page navigation without reloading the browser using React Router.
What is React Router?
React Router is a library that enables navigation between different components in a React application. It allows developers to create Single Page Applications (SPA) with a seamless user experience.
Why Use React Router?
- Faster navigation
- No page reloads
- Better user experience
- Easy route management
- Supports dynamic routing
Installation
Install React Router using npm:
npm install react-router-dom
Setting Up BrowserRouter
In the main entry file, wrap the application with BrowserRouter.
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")).render(
<BrowserRouter>
<App />
</BrowserRouter>
);
Creating Routes
Inside App.jsx, define the application routes.
import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
);
}
export default App;
Navigation Using Link
The Link component is used to navigate between pages.
import { Link } from "react-router-dom";
<Link to="/">Home</Link>
<Link to="/about">About</Link>
Unlike traditional anchor tags, Link prevents full page reloads.
Creating a Navbar
import { NavLink } from "react-router-dom";
function Navbar() {
return (
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/projects">Projects</NavLink>
</nav>
);
}
Benefits of Keeping Navbar in App.jsx
A common mistake is adding the Navbar component to every page. Instead, place it once inside App.jsx.
Advantages:
- No duplicate code
- Easier maintenance
- Consistent navigation
- Better application structure
Real-World Example
Portfolio websites commonly use React Router for navigation between:
- Home
- About
- Skills
- Projects
- Experience
- Education
- Contact
This creates a professional and organized user experience.
Conclusion
React Router is an essential library for React developers. It simplifies navigation, improves performance, and helps create modern Single Page Applications. Understanding routing is an important step toward building professional React projects such as portfolios, dashboards, and e-commerce applications.
Top comments (0)