In React Router, route guards are used to implement authentication and authorization checks for routes. It allows you to restrict access to certain routes based on user authentication status or user roles.
To implement route guards, you can create a PrivateRoute
component that wraps the Route
component from React Router. This PrivateRoute
component can check if the user is authenticated and authorized to access the route, and render the appropriate component or redirect to a login page if necessary.
Here's an example implementation of a PrivateRoute
component:
1const isLoggedIn = false;
2
3function PrivateRoute({ component: Component, ...rest }) {
4 return (
5 <Route
6 {...rest}
7 render={props =>
8 isLoggedIn ? (
9 <Component {...props} />
10 ) : (
11 <Redirect to='/login' />
12 )
13 }
14 />
15 );
16}
In this example, the PrivateRoute
component checks the isLoggedIn
variable to determine if the user is authenticated. If the user is authenticated, the PrivateRoute
component renders the specified Component
for the route. Otherwise, it redirects the user to the '/login' route.
You can use the PrivateRoute
component in your route configurations to protect specific routes that require authentication.
1import { BrowserRouter, Switch } from 'react-router-dom';
2
3function App() {
4 return (
5 <BrowserRouter>
6 <Switch>
7 <Route exact path='/' component={Home} />
8 <PrivateRoute exact path='/dashboard' component={Dashboard} />
9 <PrivateRoute exact path='/profile' component={Profile} />
10 <Route exact path='/login' component={Login} />
11 <Route component={NotFound} />
12 </Switch>
13 </BrowserRouter>
14 );
15}
In this example, the '/dashboard' and '/profile' routes are protected by the PrivateRoute
component, which requires the user to be authenticated to access those routes. If the user is not authenticated, they will be redirected to the '/login' route.
You can customize the PrivateRoute
component to include additional logic for authorization checks, such as checking user roles or permissions before allowing access to certain routes.
By using route guards, you can implement authentication and authorization checks for routes in your React Router application.
xxxxxxxxxx
const isLoggedIn = false;
function PrivateRoute({ component: Component, rest }) {
return (
<Route
{rest}
render={props =>
isLoggedIn ? (
<Component {props} />
) : (
<Redirect to='/login' />
)
}
/>
);
}