Navigation in React: A Complete Guide with Examples
React is a powerful library for building dynamic user interfaces, but on its own, it doesn’t come with built-in routing or navigation support. That’s where React Router comes in — it’s the standard library for routing in React applications.
🔹 Why Navigation Matters
In any multi-page application, users need to move between different views like Home, About, Contact, Product Details, etc. Navigation handles this and lets you show the right component based on the URL without reloading the page.
🔹 Setting Up React Router
First, install the package:
npm install react-router-dom
Then, wrap your app in a <BrowserRouter>
component in index.js
:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
🔹 Basic Example with Routes
In your App.js
file:
import { Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<div>
<nav>
<Link to="/">Home</Link> |
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={ } />
<Route path="/about" element={ } />
</Routes>
</div>
);
}
🔹 Using URL Parameters
Let’s say we have a user profile page like /user/101
. Here’s how we handle dynamic parameters:
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <h2>User ID: {id}</h2>;
}
Then in App.js
:
<Route path="/user/:id" element={ } />
🔹 Nested Routes
React Router also supports nesting components. For example, a dashboard with tabs:
<Route path="/dashboard" element={ } />
<Route path="profile" element={ } />
</Route>
Then in Dashboard.js
:
import { Outlet, Link } from 'react-router-dom';
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<nav>
<Link to="stats">Stats</Link> |
<Link to="profile">Profile</Link>
</nav>
<Outlet />
</div>
);
}
🔹 Navigate Programmatically
Sometimes you need to navigate after some logic (e.g., after login). Use the useNavigate
hook:
import { useNavigate } from 'react-router-dom';
function LoginButton() {
const navigate = useNavigate();
function handleLogin() {
// your login logic
navigate('/dashboard');
}
return <button onClick={handleLogin}>Login</button>;
}
🔹 Handling 404 Pages
<Route path="*" element={<h2>Page Not Found</h2>} />
📌 Final Thoughts
- Use
Link
instead of<a>
to avoid full page reloads. - Organize routes in a separate file if your app grows.
- React Router v6 (latest) uses
element
instead ofcomponent
.
🔗 More Learning
Start simple, and as your app grows, React Router will grow with you. Happy Routing! 🚀
0 Comments