Design Converter
Education
Last updated on Mar 12, 2025
•7 mins read
Last updated on Mar 12, 2025
•7 mins read
Software Development Executive - II
I know who I am.
How do single-page applications (SPAs) switch between views without reloading the entire page?
The secret is React Router. It handles client-side routing in React apps, letting users navigate between different components without refreshing the page. This makes the user experience smoother and faster. Setting up a proper React Router configuration helps control routes, define paths, and manage navigation with ease.
To start using React Router and configure it, you need to install React Router using npm or yarn:
1npm install react-router-dom
or
1yarn add react-router-dom
Then, import React Router in your app:
1import { BrowserRouter } from 'react-router-dom';
Set up the router in your main App component using the Router component:
1import React from 'react'; 2import { BrowserRouter } from 'react-router-dom'; 3 4function App() { 5 return ( 6 <BrowserRouter> 7 {/* Your routes here */} 8 </BrowserRouter> 9 ); 10} 11 12export default App;
To create routes, use the <BrowserRouter>
, <Routes>
, and <Route>
components. Define a route path for each component:
1import React from 'react'; 2import { BrowserRouter, Routes, Route } from 'react-router-dom'; 3import Home from './Home'; 4import About from './About'; 5import Contact from './Contact'; 6 7function App() { 8 return ( 9 <BrowserRouter> 10 <Routes> 11 <Route path="/" element={<Home />} /> 12 <Route path="/about" element={<About />} /> 13 <Route path="/contact" element={<Contact />} /> 14 </Routes> 15 </BrowserRouter> 16 ); 17} 18 19export default App;
To define and export a Contact component, you can use the export default
syntax:
1import React from 'react'; 2 3function Contact() { 4 return <div>Contact Page</div>; 5} 6 7export default Contact;
To set up React Router, wrap your app component in <BrowserRouter>
within the index.js file:
1import React from 'react'; 2import ReactDOM from 'react-dom'; 3import App from './App'; 4import { BrowserRouter } from 'react-router-dom'; 5 6ReactDOM.createRoot(document.getElementById('root')).render( 7 <BrowserRouter> 8 <App /> 9 </BrowserRouter> 10);
Use the useNavigate hook to navigate programmatically:
1import { useNavigate } from 'react-router-dom'; 2 3function MyComponent() { 4 const navigate = useNavigate(); 5 6 const handleClick = () => { 7 navigate('/about'); 8 }; 9 10 return ( 11 <button onClick={handleClick}>Go to About</button> 12 ); 13}
Use the useParams hook to get URL parameters and render dynamic components:
1import { useParams } from 'react-router-dom'; 2 3function ProductPage() { 4 const { productId } = useParams(); 5 6 return ( 7 <div> 8 <h1>Product {productId}</h1> 9 </div> 10 ); 11}
Use nested <Route>
components within a parent <Route>
in <Routes>
:
1import React from 'react'; 2import { BrowserRouter, Routes, Route } from 'react-router-dom'; 3import Dashboard from './Dashboard'; 4import RecentActivity from './RecentActivity'; 5import Project from './Project'; 6 7function App() { 8 return ( 9 <BrowserRouter> 10 <Routes> 11 <Route path="/dashboard" element={<Dashboard />}> 12 <Route index element={<RecentActivity />} /> 13 <Route path="project/:id" element={<Project />} /> 14 </Route> 15 </Routes> 16 </BrowserRouter> 17 ); 18} 19 20export default App;
Use the Navigate component within <Routes>
to handle redirects:
1import { Navigate } from 'react-router-dom'; 2 3function App() { 4 return ( 5 <BrowserRouter> 6 <Routes> 7 <Route path="/old-path" element={<Navigate to="/new-path" />} /> 8 </Routes> 9 </BrowserRouter> 10 ); 11}
In many applications, certain routes should only be accessible to authenticated users. This is where route guards come into play. Route guards ensure that users are redirected to a login page if they attempt to access a protected route without proper authentication.
To implement route guards in React Router, you can use the useNavigate hook to programmatically redirect users. Additionally, the useLocation hook helps you retrieve the current URL, which can be useful for checking authentication status.
Here’s an example of how to set up a simple route guard:
1import React from 'react'; 2import { BrowserRouter, Routes, Route, useNavigate, useLocation } from 'react-router-dom'; 3import Home from './Home'; 4import Dashboard from './Dashboard'; 5import Login from './Login'; 6 7const ProtectedRoute = ({ element: Component, ...rest }) => { 8 const navigate = useNavigate(); 9 const location = useLocation(); 10 const isAuthenticated = false; // Replace with actual authentication logic 11 12 if (!isAuthenticated) { 13 navigate('/login', { state: { from: location } }); 14 return null; 15 } 16 17 return <Component {...rest} />; 18}; 19 20function App() { 21 return ( 22 <BrowserRouter> 23 <Routes> 24 <Route path="/" element={<Home />} /> 25 <Route path="/login" element={<Login />} /> 26 <Route path="/dashboard" element={<ProtectedRoute element={Dashboard} />} /> 27 </Routes> 28 </BrowserRouter> 29 ); 30} 31 32export default App;
Lazy loading is a technique used to load components only when they are needed, which can significantly improve the performance of your application. In React Router, you can use the lazy function to create lazy-loaded components, and the Suspense component to handle the loading state.
Here’s how you can implement lazy loading in your React app:
1import React, { lazy, Suspense } from 'react'; 2import { BrowserRouter, Routes, Route } from 'react-router-dom'; 3 4const Home = lazy(() => import('./Home')); 5const About = lazy(() => import('./About')); 6 7function App() { 8 return ( 9 <BrowserRouter> 10 <Suspense fallback={<div>Loading...</div>}> 11 <Routes> 12 <Route path="/" element={<Home />} /> 13 <Route path="/about" element={<About />} /> 14 </Routes> 15 </Suspense> 16 </BrowserRouter> 17 ); 18} 19 20export default App;
Only when their corresponding routes are hit do the Home and About components in this example load. While the lazy-loaded components are being retrieved, the Suspense component shows a fallback user interface (in this case, a loading message).
Sometimes, you may need to define custom logic for matching routes. React Router provides the useRouteMatch and useParams hooks to help you achieve this.
The useRouteMatch hook returns information about how a <Route>
matches the URL, while the useParams hook retrieves the parameters from the URL.
Here’s an example of custom route matching:
1import React from 'react'; 2import { BrowserRouter, Routes, Route, useRouteMatch, useParams } from 'react-router-dom'; 3 4const CustomComponent = () => { 5 const match = useRouteMatch('/custom/:id'); 6 const { id } = useParams(); 7 8 if (!match) { 9 return <div>Route not matched</div>; 10 } 11 12 return <div>Custom Route Matched with ID: {id}</div>; 13}; 14 15function App() { 16 return ( 17 <BrowserRouter> 18 <Routes> 19 <Route path="/custom/:id" element={<CustomComponent />} /> 20 </Routes> 21 </BrowserRouter> 22 ); 23} 24 25export default App;
In this example, the CustomComponent uses useRouteMatch to check if the current route matches /custom/:id
and useParams to extract the id
parameter from the URL.
Integrating React Router with state management libraries like Redux or MobX can help you manage the state of your application more effectively.
To integrate React Router with Redux, you can use the react-router-redux
library. For MobX, the mobx-react-router
library is available.
Here’s an example of integrating React Router with Redux:
1import React from 'react'; 2import { BrowserRouter, Routes, Route } from 'react-router-dom'; 3import { Provider, useSelector } from 'react-redux'; 4import { createStore } from 'redux'; 5import rootReducer from './reducers'; 6import Home from './Home'; 7import Dashboard from './Dashboard'; 8 9const store = createStore(rootReducer); 10 11const ProtectedRoute = ({ element: Component, ...rest }) => { 12 const isAuthenticated = useSelector(state => state.auth.isAuthenticated); 13 14 if (!isAuthenticated) { 15 return <div>Access Denied</div>; 16 } 17 18 return <Component {...rest} />; 19}; 20 21function App() { 22 return ( 23 <Provider store={store}> 24 <BrowserRouter> 25 <Routes> 26 <Route path="/" element={<Home />} /> 27 <Route path="/dashboard" element={<ProtectedRoute element={Dashboard} />} /> 28 </Routes> 29 </BrowserRouter> 30 </Provider> 31 ); 32} 33 34export default App;
In this example, the ProtectedRoute component uses the useSelector hook to access the Redux state and check if the user is authenticated before rendering the Dashboard component.
Use the Suspense component to implement lazy loading:
1import { Suspense } from 'react'; 2import { BrowserRouter, Routes, Route } from 'react-router-dom'; 3import Home from './Home'; 4 5function App() { 6 return ( 7 <BrowserRouter> 8 <Routes> 9 <Route 10 path="/" 11 element={ 12 <Suspense fallback={<div>Loading...</div>}> 13 <Home /> 14 </Suspense> 15 } 16 /> 17 </Routes> 18 </BrowserRouter> 19 ); 20}
Mastering React Router configuration makes it easier to build smooth and user-friendly single-page applications. Understanding how to set up routes, navigate programmatically, and improve performance helps developers create a better user experience. React Router gives developers the tools to handle client-side routing effectively, whether working on a small project or a large enterprise app.
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.