Understanding React Outlet: A Comprehensive Guide
React is a powerful JavaScript library for building user interfaces. One of its key features is React Router, which allows developers to create dynamic, single-page applications with multiple views. In this blog post, we’ll explore React Outlet, an essential part of React Router, and understand its role in managing nested routes within a React application.
What is React Outlet?
React Outlet is a component provided by React Router that serves as a placeholder for child routes within a parent route. It allows for the nesting of routes, enabling developers to create complex navigation structures in their applications.
import React from "react";
// import components
import Routes from "./routes";
// component
const App = () => {
return (
<>
<Routes />
</>
);
};
export default App;
// import packages
import { BrowserRouter, Outlet, Route, Routes } from "react-router-dom";
import React, { Suspense, lazy } from "react";
import {
dashboard,
homePath,
loginPath,
rootPath
} from "./routePaths";
import Loader from "../components/loader";
import ProtectedRoute from "./protectedRoute";
// import route paths
const Login = lazy(() => import("../pages/login"));
const Home = lazy(() => import("../pages/home"));
const RouteNotFound = lazy(() => import("../pages/pageNotFound"));
const DashboardComponent = lazy(() => import("../pages/dashboard/"));
const AllRoutes = () => {
return (
<Suspense fallback={<Loader />}>
<BrowserRouter>
<Routes>
<Route path={rootPath} element={<Outlet />}>//--------------gives access to child component
<Route index element={<Login />} /> //------------showing / route component
<Route path={loginPath} element={<Login />} />
{/* <Route path={accessErrorPage} element={<AccessErrorPage />} /> */}
<Route element={<ProtectedRoute />}>
<Route path={homePath} element={<Home />} />
<Route path={dashboard} element={<DashboardComponent />} />
</Route>
<Route path="*" element={<RouteNotFound />} />
</Route>
</Routes>
</BrowserRouter>
</Suspense>
);
};
export default AllRoutes;
- App Component:
- The
App
component is the entry point of our React application. - It renders the
Routes
component, which handles the routing of our application.
2.AllRoutes Component:
- The
AllRoutes
component sets up the routes for our application using React Router. - It defines routes for different paths and lazy-loads components using the
Suspense
component for better performance. - Inside the routes, it utilizes the
Outlet
component to handle nested routes.
All in All
- Imports: we are importing necessary components and functions from
react-router-dom
, as well as other components and route paths from your project. - Lazy Loading: we are using
lazy()
from React to lazily load components. This improves initial load time by splitting the bundle into smaller chunks that are loaded on demand. - Suspense: we are using the
<Suspense>
component to wrap your lazy-loaded routes. This allows you to specify a fallback UI while the components are loading. - Routing: Inside your
<Routes>
component, we are defining different routes using the<Route>
component. Here's a breakdown of the routes:
- Root Route (
/
): This route is for the root path of our application. It renders theLogin
component. - Login Route (
/login
): This route renders theLogin
component.
5. Protected Routes: These routes are wrapped inside a <ProtectedRoute>
component. This likely handles authentication logic to restrict access to certain routes. Inside the protected routes, you have:
- Home Route (
/home
): Renders theHome
component. - Dashboard Route (
/dashboard
): Renders theDashboardComponent
component. - Wildcard Route (
*
): This route matches any path that doesn't match the previous routes and renders theRouteNotFound
component.
6. BrowserRouter: This component provides the routing functionality to your application. It uses HTML5 history API to keep your UI in sync with the URL.
// import packages
import React, { useEffect } from "react";
import { useNavigate, Outlet } from "react-router-dom";
import BaseLayout from "../pages/layout";
// import route paths
import { rootPath } from "./routePaths";
// component
const ProtectedRoute = () => {
const navigate = useNavigate();();
const isAuthenticated = false; //add a dynamic method call
const user = 'shruti';//add a dynamic method call
useEffect(() => {
if (!isAuthenticated) {
return navigate(rootPath, { replace: true });
}
}, [isAuthenticated, navigate]);
return (
<BaseLayout >
<Outlet />
</BaseLayout>
);
};
export default ProtectedRoute;
ProtectedRoute Component:
- The
ProtectedRoute
component is responsible for protecting certain routes that require authentication. - It utilizes the
Outlet
component to render nested child routes within the protected route.
import React, { lazy } from "react";
import ErrorBoundary from "../../components/error-boundary";
// const Header = lazy(() => import("@components/header"));
const Sidebar = lazy(() => import("../../components/sidebar"));
export default function BaseLayout(props) {
const { children } = props;
// common things we need to show on each page like Header,sidebar ,Footer
return (
<ErrorBoundary>
<div className="wrapper">
<div className="d-flex position-relative">
<Sidebar />
<main className="main-container">
{/* <Header /> */}
{children}//components from all routes
</main>
</div>
</div>
</ErrorBoundary>
);
}
BaseLayout.defaultProps = {
children: [],
user: {},
};
BaseLayout Component:
- The
BaseLayout
component serves as a common layout structure for all pages in our application. - It contains common elements like a sidebar and main content area.
- Child components from different routes are rendered using the
Outlet
component within the main content area.
Understanding React Outlet:
- React Outlet is used within the
AllRoutes
component to render child routes within a parent route. - It allows for the modularization of routes, making it easier to manage complex navigation structures.
- Nested routes can have their own layouts and functionality while still being part of a larger parent route.
- By using React Outlet, developers can create more organized and maintainable codebases for their React applications.
Conclusion:
React Outlet is a powerful tool provided by React Router for managing nested routes within a React application. By understanding its usage and incorporating it into our routing setup, we can create more dynamic and flexible user interfaces. Whether it’s protecting routes, creating layouts, or handling complex navigation structures, React Outlet plays a crucial role in building robust React applications.