Design Converter
Education
Last updated on Mar 17, 2025
•6 mins read
Last updated on Mar 17, 2025
•6 mins read
Software Development Executive - I
Builds things that work. And if it doesn’t, he’ll fix it — with Neovim, of course.
Struggling with navigation in single-page applications (SPAs)?
React Router makes it easy to handle client-side routing in React apps without reloading the whole page. At the heart of React Router is the BrowserRouter component. It uses the HTML5 history API to keep the UI and URL in sync. This helps create smooth and fast navigation, improving the user experience.
Let’s break down how it works!
A key component of React Router that makes client-side routing possible in React apps is the BrowserRouter component. By utilizing the HTML5 history API, BrowserRouter allows developers to manage navigation without triggering full page reloads, resulting in a smoother user experience.
To implement routing in a React application, wrap the root component with BrowserRouter. This setup ensures that the routing context is available throughout the application.
1import React from 'react'; 2import ReactDOM from 'react-dom'; 3import { BrowserRouter } from 'react-router-dom'; 4import App from './App'; 5 6ReactDOM.render( 7 <BrowserRouter> 8 <App /> 9 </BrowserRouter>, 10 document.getElementById('root') 11);
In this configuration, BrowserRouter enables the application to handle navigation based on the browser's URL, facilitating client-side routing.
The Route component is used to define individual routes in a React application. Each Route specifies a path and the corresponding component to render when the URL matches that path.
1import React from 'react'; 2import { Routes, Route } from 'react-router-dom'; 3import Home from './components/Home'; 4import About from './components/About'; 5 6function App() { 7 return ( 8 <Routes> 9 <Route path="/" element={<Home />} /> 10 <Route path="/about" element={<About />} /> 11 </Routes> 12 ); 13} 14 15export default App;
In this example, when the URL path is /
, the Home component is rendered. Similarly, when the URL path is /about
, the About component is displayed.
To enable navigation between different routes, React Router provides the Link and NavLink components. These components allow users to navigate without triggering full page reloads, maintaining the SPA behavior.
1import React from 'react'; 2import { Link, NavLink } from 'react-router-dom'; 3 4function Navigation() { 5 return ( 6 <nav> 7 <ul> 8 <li> 9 <NavLink to="/" activeClassName="active"> 10 Home 11 </NavLink> 12 </li> 13 <li> 14 <NavLink to="/about" activeClassName="active"> 15 About 16 </NavLink> 17 </li> 18 </ul> 19 </nav> 20 ); 21} 22 23export default Navigation;
In this snippet, NavLink is used to apply an active class to the link corresponding to the current URL, enabling styling for active links.
Nested routes allow developers to render components within other components based on the URL structure. This feature is particularly useful for creating layouts with shared components like sidebars or headers.
1import React from 'react'; 2import { Routes, Route, Outlet } from 'react-router-dom'; 3 4function Dashboard() { 5 return ( 6 <div> 7 <h2>Dashboard</h2> 8 <Outlet /> 9 </div> 10 ); 11} 12 13function Analytics() { 14 return <h3>Analytics</h3>; 15} 16 17function Admin() { 18 return ( 19 <Routes> 20 <Route path="dashboard" element={<Dashboard />}> 21 <Route path="analytics" element={<Analytics />} /> 22 </Route> 23 </Routes> 24 ); 25} 26 27export default Admin;
In this example, the Dashboard component renders the Analytics component when the URL matches /dashboard/analytics
. The Outlet component serves as a placeholder for nested routes.
React Router supports dynamic routing through route parameters, allowing components to access dynamic segments of the URL. This feature is essential for rendering content based on user-specific data.
1import React from 'react'; 2import { useParams } from 'react-router-dom'; 3 4function UserProfile() { 5 const { userId } = useParams(); 6 7 return ( 8 <div> 9 <h2>User Profile</h2> 10 <p>User ID: {userId}</p> 11 </div> 12 ); 13}
Here, the useParams hook retrieves the userId parameter from the URL, allowing the UserProfile component to render content specific to that user.
In addition to declarative navigation with Link and NavLink, React Router provides the useNavigate hook for programmatic navigation. This hook enables components to navigate to different routes based on user interactions or application logic.
1import React from 'react'; 2import { useNavigate } from 'react-router-dom'; 3 4function Login() { 5 const navigate = useNavigate(); 6 7 const handleLogin = () => { 8 // Perform login logic 9 navigate('/dashboard'); 10 }; 11 12 return ( 13 <div> 14 <h2>Login</h2> 15 <button onClick={handleLogin}>Log In</button> 16 </div> 17 ); 18} 19 20export default Login;
In this example, upon successful login, the application navigates the user to the dashboard using the useNavigate hook. This hook, introduced in React Router v6, replaces the older useHistory hook, providing a more streamlined API for programmatic navigation within React applications.
In any web application, it's essential to manage scenarios where users navigate to undefined routes. React Router offers mechanisms to handle such cases gracefully, ensuring users receive appropriate feedback instead of encountering broken pages.
To address undefined routes, you can define a catch-all route that renders a specific component when no other routes match the current URL. This is typically used to display a "404 Not Found" page.
1import React from 'react'; 2import { Routes, Route, useLocation } from 'react-router-dom'; 3 4function NoMatch() { 5 let location = useLocation(); 6 7 return ( 8 <div> 9 <h3> 10 No match for <code>{location.pathname}</code> 11 </h3> 12 </div> 13 ); 14} 15 16function App() { 17 return ( 18 <Routes> 19 <Route path="/" element={<Home />} /> 20 <Route path="/about" element={<About />} /> 21 {/* Catch-all route */} 22 <Route path="*" element={<NoMatch />} /> 23 </Routes> 24 ); 25} 26 27export default App;
In this configuration, the NoMatch component is rendered for any URL path that doesn't match the defined routes. The useLocation hook provides access to the current location object, allowing you to display the unmatched path.
React Router's Navigate component enables declarative redirection. For instance, you can redirect users from an old route to a new one seamlessly.
1import React from 'react'; 2import { Routes, Route, Navigate } from 'react-router-dom'; 3 4function App() { 5 return ( 6 <Routes> 7 <Route path="/" element={<Home />} /> 8 <Route path="/new-path" element={<NewComponent />} /> 9 {/* Redirect from old path */} 10 <Route path="/old-path" element={<Navigate to="/new-path" replace />} /> 11 <Route path="*" element={<NoMatch />} /> 12 </Routes> 13 ); 14} 15 16export default App;
In this example, any navigation to /old-path
automatically redirects to /new-path
, ensuring users access the updated route without encountering errors.
Understanding React Router BrowserRouter makes handling client-side routing much easier. By setting up routes with the Route component, using Link and NavLink for navigation, and managing dynamic routing with route parameters, developers can create smooth user experiences. The useNavigate hook also helps with programmatic navigation, while handling no-match routes ensures users aren't left confused. Mastering these basics of React Router helps in building single-page applications that feel fast and easy to use.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.