PrivateRoute Component
The PrivateRoute component restricts access to certain routes based on the presence of an authentication token. It is used to ensure that only authenticated users can access certain parts of your application.
Features
- Route Protection: The component checks if a
tokenis present. If the token exists, the requested component (element) is rendered. If not, the user is redirected to the specified path (redirectTo). - Redirects Unauthenticated Users: If no
tokenis provided, the user is redirected to a login page or another specified route.
Props
PrivateRouteProps
- token: A string representing the authentication token. If the token is not provided or is
undefined, the user will be redirected. Default isundefined. - element: The React element to render if the user is authenticated.
- redirectTo: A string representing the path to redirect unauthenticated users to (e.g., a login page).
Example
import React from 'react';
import PrivateRoute from './path/to/PrivateRoute';
import Dashboard from './path/to/Dashboard';
// Example: Protecting the Dashboard route
const App = () => {
const token = localStorage.getItem('authToken'); // Get token from local storage or other source
return (
<PrivateRoute
token={token}
element={<Dashboard />}
redirectTo="/login"
/>
);
};
export default App;
Default Behavior
- Authenticated Access: If the
tokenprop is provided, theelementis rendered. - Redirect on Missing Token: If no
tokenis found, the user is redirected to theredirectTopath.
Notes
- The
PrivateRoutecomponent relies on theNavigatecomponent fromreact-router-domfor redirecting users. - You can use this component to protect any route or part of your application that should only be accessible to authenticated users.
- Make sure to handle token retrieval securely, such as from cookies or local storage, depending on your application's authentication strategy.