For working professionals
For fresh graduates
More
5. React Table
8. Context API
The React Router DOM is a popular routing library for React applications. The DOM library is an efficient tool for handling client-side routing, organized application structure, nested routing, integration with React ecosystems, dynamic routing, and history management.
React Router DOM handles both client-side and dynamic routing. It handles client-side routing by how React Router DOM enhances Single Page Applications (SPAs). It also handles dynamic routing because it often contains content that changes depending on user interactions or data fetched from a server.
You can read this post to get an insight into the basic concept of react routing DOM. Get to understand concepts like routers, links, and navigation.
There are some prerequisites that you must check off your list before you utilize the library. You are required to have the following before getting started with the Router DOM.
The section below offers a step-by-step guide for setting up the React ecosystem.
Follow the prompts below to start the React Router DOM installation process.
Basic Setup in a React Application
Setting up React Router DOM in a React application involves a few steps, and below are highlights of the process.
npx create-react-app my-app
cd my-app
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
function App() {
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</Router>
);
}
export default App;
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the Home Page!</p>
</div>
);
};
export default Home;
You can repeat the same process for the About and Contact components.
npm start.
Configuring React Router DOM in the index.js or App.js file is essential for setting up routing in your React application. Follow the steps below to embark on the configuration process.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom'; // Import BrowserRouter
ReactDOM.render(
<BrowserRouter> {/* Wrap your App component with BrowserRouter */}
<App />
</BrowserRouter>,
document.getElementById('root')
);
React Router DOM contains core components like the <BrowserRouter>, <Routes>, <Route>, <Link>, and <Outlet> components. Below is a highlight of the various Router DOM components.
The <BrowseRouter> component is an essential wrapper for your application. It utilizes HTML5 history API to keep your UI in sync with the URL. Below is a sample code for the <BrowseRouters> component.
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
The <Routes> component is essential for defining application routes. It replaces the <Switch> component from previous versions of React Router. It renders the first <Route> or <Redirect> that matches the current URL. Below is an illustration of how you can use the Router DOM component.
import { Routes, Route } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
);
}
The <Route> component renders the UI based on the URL path. Below is a sample code of the <Route> component.
import { Route } from 'react-router-dom';
<Route path="/about" element={<About />} />
<Route path="/products/:id" element={<ProductDetail />} />
You can use the <Link> component to navigate between different views in your application without a full page reload. Below is an example of how to use the component.
import { Link } from 'react-router-dom';
<Link to="/about">About Us</Link>
<Link to={`/products/${productId}`}>Product Details</Link>
The <Outlet> component is essential for rendering child routes within their parent route's component. Below is an example of the <Outlet> component.
import { Outlet } from 'react-router-dom';
function Products() {
return (
<div>
<h1>Products</h1>
<Outlet /> {/* Renders child routes */}
</div>
);
}
Advanced routing concepts extend beyond the basic concepts, and you can expect to utilize concepts such as dynamic routing, nested routes, and programmatic navigation. The section highlights the three common advanced routing concepts.
Dynamic routing involves using path parameters to create routes that respond dynamically to changes in the URL. The useParams hook is a powerful tool for accessing and extracting parameters from the URL within their components, enabling dynamic rendering and data fetching based on the URL parameters.
Below is an example of how to use the useParams hook in dynamic routing.
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useParams } from 'react-router-dom';
// Define components for different pages
const Home = () => <h1>Home Page</h1>;
const About = () => <h1>About Page</h1>;
const Contact = () => <h1>Contact Page</h1>;
// UserProfile component using useParams hook to access username parameter
const UserProfile = () => {
const { username } = useParams();
return <h1>User Profile: {username}</h1>;
};
const App = () => {
return (
<Router>
<nav>
{/* Navigation links */}
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
<li><Link to="/profile/johndoe">User Profile (John Doe)</Link></li>
<li><Link to="/profile/janesmith">User Profile (Jane Smith)</Link></li>
</ul>
</nav>
{/* Define routes */}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
{/* Dynamic route for user profiles */}
<Route path="/profile/:username" element={<UserProfile />} />
</Routes>
</Router>
);
}
export default App;
They help organize routing configuration into smaller, more manageable pieces. Below is a practical example of how to use the nested routes component.
Apps.js
// 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';
const App = () => {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
}
export default App;
Home.js
// Home.js
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the Home Page!</p>
</div>
);
}
export default Home;
About.js
// About.js
import React from 'react';
const About = () => {
return (
<div>
<h1>About Page</h1>
<p>This is the About Page.</p>
</div>
);
}
export default About;
Contact.js
// Contact.js
import React from 'react';
const Contact = () => {
return (
<div>
<h1>Contact Page</h1>
<p>Contact us at example@example.com.</p>
</div>
);
}
export default Contact;
You can use the UseHistory / UseNavigate hooks to redirect users programmatically, as shown below.
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useHistory, useNavigate } from 'react-router-dom';
const Home = () => {
const history = useHistory();
const handleClick = () => {
// Redirect to the About page programmatically
history.push('/about');
};
return (
<div>
<h1>Home Page</h1>
<button onClick={handleClick}>Go to About</button>
</div>
);
}
const About = () => {
const navigate = useNavigate();
const handleClick = () => {
// Redirect to the Home page programmatically
navigate('/');
};
return (
<div>
<h1>About Page</h1>
<button onClick={handleClick}>Go to Home</button>
</div>
);
}
const App = () => {
return (
<Router>
<div>
<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>
</div>
</Router>
);
}
export default App;
This subsection highlights the concepts of protected routes, implementing authentication flow, and use of higher-order components (HOCs) or context API for protecting routes.
The concept of protected routes in React Routing DOM involves configuring routes that are accessible only to authenticated users. You can achieve this by wrapping them in a higher-order component or using conditional rendering based on the user's authentication status.
This concept involves setting up routes for login, registration, and protected content, integrating authentication logic to manage user sessions or tokens. It also involves employing higher-order components or custom hooks to control access to protected routes based on the user's authentication status, thus redirecting unauthorized users to a login page.
Optimizing performance involves practicing concepts such as code splitting with React.lazy and Suspense, efficient route rendering, and avoiding unnecessary renders in your code.
Common patterns and practices in React Router DOM include:
In a rejoinder, the latest React Router DOM offers a robust client-side routing solution for applications. You can leverage its potential to build scalable and SEO-friendly applications that deliver a seamless user experience across different views and interactions.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.