React JS: Routing & Navigation
Routing is a fundamental aspect of building multi-page applications with React. It allows users to navigate between different "views" or "pages" without requiring a full page reload, providing a smoother and more dynamic user experience. React Router is the most popular library for handling routing in React applications.
Why Use Routing?
- Single-Page Application (SPA) Experience: Routing enables the creation of SPAs, where content is dynamically updated within a single HTML page.
- Improved User Experience: Faster navigation and a more responsive feel.
- SEO Considerations: While SPAs historically had SEO challenges, modern techniques (like server-side rendering) mitigate these.
- Maintainability: Organized code structure by separating different parts of your application into distinct routes.
React Router: Core Concepts
BrowserRouter: Uses the HTML5 history API (pushState,replaceState) for clean URLs. Suitable for most web applications.HashRouter: Uses the hash portion of the URL (#) for routing. Useful when you can't configure the server to handle direct routing (e.g., static hosting).Routes: A container for individualRoutecomponents. Introduced in React Router v6.Route: Defines a mapping between a URL path and a React component. When the current URL matches thepathprop, the associatedelement(component) is rendered.Link: A component that creates an<a>tag with special behavior for navigating between routes without a full page reload. Usestoprop to specify the target path.NavLink: Similar toLink, but adds styling capabilities (e.g., active class) when the link is currently active.useNavigate: A hook that provides access to the navigation function, allowing programmatic navigation.useParams: A hook that allows you to access dynamic parameters from the URL.useLocation: A hook that provides access to the current location object, including the pathname, search parameters, and hash.
Basic Implementation (React Router v6)
Install React Router:
npm install react-router-dom # or yarn add react-router-domWrap your App with
BrowserRouter:import { BrowserRouter } from 'react-router-dom'; function App() { return ( <BrowserRouter> {/* Your routes will go here */} </BrowserRouter> ); } export default App;Define Routes using
RoutesandRoute:import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; function Home() { return <h1>Home</h1>; } function About() { return <h1>About</h1>; } function App() { return ( <BrowserRouter> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); } export default App;
Dynamic Routing (Route Parameters)
To create routes that accept parameters (e.g., /users/123, /products/:id), use dynamic segments in the path prop.
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';
function User() {
const { userId } = useParams();
return <h1>User ID: {userId}</h1>;
}
function App() {
return (
<BrowserRouter>
<nav>
<ul>
<li>
<Link to="/users/123">User 123</Link>
</li>
<li>
<Link to="/users/456">User 456</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/users/:userId" element={<User />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Programmatic Navigation
Use the useNavigate hook to navigate programmatically.
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/about'); // Navigate to the /about route
};
return <button onClick={handleClick}>Go to About</button>;
}
You can also use navigate with relative paths:
navigate(-1); // Go back one page
navigate(1); // Go forward one page
navigate('./contact'); // Navigate to ./contact relative to the current path
Nested Routes
You can nest routes to create more complex application structures.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<ul>
<li><Link to="/dashboard/profile">Profile</Link></li>
<li><Link to="/dashboard/settings">Settings</Link></li>
</ul>
</div>
);
}
function Profile() {
return <h1>Profile</h1>;
}
function Settings() {
return <h1>Settings</h1>;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={<Dashboard />} >
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Handling 404 (Not Found)
Add a route with a wildcard path (*) to handle unmatched routes.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function NotFound() {
return <h1>404 Not Found</h1>;
}
function App() {
return (
<BrowserRouter>
<Routes>
{/* Other routes */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Common Use Cases
- Authentication: Redirect unauthenticated users to a login page.
- Authorization: Control access to routes based on user roles.
- Dynamic Content: Fetch data based on route parameters.
- Complex Layouts: Use nested routes to manage different sections of your application.
Resources
- React Router Documentation: https://reactrouter.com/
- React Router Tutorials: Numerous tutorials available on platforms like YouTube and blogs.