Introduction
As React applications grow, managing navigation between different views becomes essential. Instead of reloading the entire page, React allows single-page applications (SPAs) where components dynamically render based on the URL. This behavior is achieved through routing.
React Router is the most popular library for handling routing in React. It provides declarative tools to define routes and render components based on the current URL.
In this post, we will cover:
- Creating multiple pages/components
- Defining routes using
Routeandpath - Rendering components dynamically based on URL
- A practical example with Home, About, and Contact pages
Installing React Router
Before creating routes, install the React Router library:
npm install react-router-dom
react-router-domis the package for browser-based routing.- Provides components like
BrowserRouter,Routes,Route, andLink.
Creating Multiple Pages/Components
React routing relies on separate components representing different pages.
Example Components
// Home.js
import React from 'react';
function Home() {
return <h1>Welcome to the Home Page</h1>;
}
export default Home;
// About.js
import React from 'react';
function About() {
return <h1>About Us</h1>;
}
export default About;
// Contact.js
import React from 'react';
function Contact() {
return <h1>Contact Page</h1>;
}
export default Contact;
- Each component represents a distinct page in the app.
- Components can include more complex JSX, forms, or API calls.
Defining Routes with Route and Path
React Router uses the Route component to associate a URL path with a component.
Basic Routing Setup
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
export default App;
Explanation:
BrowserRouter(aliased asRouter) wraps the entire app to enable routing.Routescontains allRoutedefinitions.- Each
Routehas apathand anelementto render. - Visiting
/aboutrenders the About component,/contactrenders Contact.
Navigating Between Pages
To navigate without reloading the page, use the Link component instead of <a> tags.
Example Navigation
import React from 'react';
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
);
}
export default Navbar;
Key Points:
toprop specifies the target route.- Clicking a link updates the URL and renders the corresponding component without reloading the page.
Nested Routes
React Router allows nested routes for layouts or sub-pages.
// Dashboard.js
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import Profile from './Profile';
import Settings from './Settings';
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<Link to="profile">Profile</Link>
<Link to="settings">Settings</Link>
</nav>
<Routes>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Routes>
</div>
);
}
export default Dashboard;
- Nested routes allow sub-components under a parent path.
- Visiting
/dashboard/profilerenders the Profile component inside Dashboard.
Dynamic Routes
Routes can be dynamic with parameters in the URL.
import React from 'react';
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <h2>User ID: {id}</h2>;
}
// Route definition
<Route path="/user/:id" element={<User />} />
:idis a route parameter.useParamshook retrieves the parameter value.- Useful for detail pages, profiles, or dynamic content.
Handling 404 Pages
To display a fallback for undefined routes, use a wildcard path:
function NotFound() {
return <h1>404 - Page Not Found</h1>;
}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<NotFound />} />
</Routes>
- The
*path matches all unmatched URLs. - Ensures users see a meaningful message for invalid routes.
Example: Home, About, Contact Pages
Complete App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import NotFound from './NotFound';
function App() {
return (
<Router>
<header>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
</header>
<main>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<NotFound />} />
</Routes>
</main>
</Router>
);
}
export default App;
- Combines routing, navigation, and fallback page.
- Each page is a separate component.
- Navigation links dynamically update the content.
Best Practices for Routing
- Keep routes declarative with
RoutesandRoute. - Use nested routes for layouts or sections.
- Use
Linkinstead of<a>to prevent page reloads. - Handle 404 pages for unknown routes.
- Use route parameters for dynamic content.
- Organize components by route or feature for clarity.
- Lazy load routes for performance optimization in large apps.
Leave a Reply