Exploring Outlet, Navigate, and useLocation
let’s dive into three important parts of React Router DOM: Outlet, Navigate, and useLocation.
Imagine this: depending on whether a user is logged in or not, the app behaves differently. If they’re logged in, they can access certain parts of the app. If not,they’re directed to the login page.
// src/App.js
import React from 'react';
import { Outlet, Navigate, Route, Routes, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { Home, Login, Profile, Register, ResetPassword } from './pages';
function Layout() {
const { user } = useSelector((state) => state.user);
const location = useLocation(); // Get the current location
return user?.token ? (
<Outlet /> // Render child routes if user is authenticated
) : (
<Navigate to="/login" state={{ from: location }} replace /> // Redirect to login if not authenticated
);
}
function App() {
const { theme } = useSelector((state) => state.theme);
return (
<div data-theme={theme} className="w-full min-h-[100vh]">
<Routes>
{/* Parent route with Layout */}
<Route element={<Layout />}>
<Route path="/" element={<Home />} /> {/* Home page */}
<Route path="/profile/:id?" element={<Profile />} /> {/* Profile page */}
</Route>
{/* Other top-level routes */}
<Route path="/register" element={<Register />} /> {/* Registration page */}
<Route path="/login" element={<Login />} /> {/* Login page */}
<Route path="/reset-password" element={<ResetPassword />} /> {/* Reset password page */}
</Routes>
</div>
);
}
export default App;
Deep Dive:
- Outlet:
The <Outlet /> component is used to render child routes. If the user is authenticated (has a token), the child routes are rendered.
- Navigate:
The <Navigate /> component is used to redirect to different routes. If the user is not authenticated, they are redirected to the login page. This is a great way to handle authentication in application.
- useLocation:
The useLocation hook is used to get the current location.
By including the state property with the from key set to the location object, we enable our application to remember and restore the user's intended navigation path after successful authentication, thereby enhancing the overall user experience.