React Router is a powerful library that enables navigation and routing in React applications. It allows developers to manage application views efficiently, creating a smooth user experience similar to traditional websites.
After completing this material, you should be able to:
react-router-dom package.Outlet component.react-router-dom package.useParams hook to access path variables.Navigate component and useNavigate hook to redirect users and/or programmatically change the browser's URL.To define routes in your React application, use the react-router-dom package:
import {{ BrowserRouter as Router, Routes, Route }} from "react-router-dom";
function App() {{
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}}
The Outlet component is used in parent routes to render nested child components dynamically.
import {{ Outlet }} from "react-router-dom";
function Layout() {{
return (
<div>
<h1>My App</h1>
<Outlet />
</div>
);
}}
To create navigable links, use the Link and NavLink components.
import {{ Link, NavLink }} from "react-router-dom";
function Navigation() {{
return (
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
</nav>
);
}}
The useParams hook allows access to dynamic segments in the URL.
import {{ useParams }} from "react-router-dom";
function UserProfile() {{
let {{ userId }} = useParams();
return <h2>User ID: {{ userId }}</h2>;
}}
The Navigate component and useNavigate hook enable programmatic navigation.
import {{ Navigate, useNavigate }} from "react-router-dom";
function RedirectComponent() {{
return <Navigate to="/home" />;
}}
function ButtonNavigation() {{
let navigate = useNavigate();
return <button onClick={() => navigate("/dashboard")}>Go to Dashboard</button>;
}}
To deepen your understanding, explore these topics:
React Router is essential for managing navigation in React applications. By mastering its features, developers can create dynamic, user-friendly, and scalable applications.