In React, route guards are used to control access to certain routes based on certain conditions, like authentication. You can implement route guards using React Router to conditionally render components based on logic, such as whether a user is logged in or has the required permissions.
Here’s an example of how to create a simple route guard for authenticated users:
1. Install react-router-dom
:
npm install react-router-dom
2. Create a PrivateRoute
component:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
export default PrivateRoute;
3. Use PrivateRoute
in your app:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import HomePage from './HomePage';
import Dashboard from './Dashboard';
import Login from './Login';
import PrivateRoute from './PrivateRoute';
function App() {
const isAuthenticated = // Your logic for checking authentication
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<PrivateRoute
path="/dashboard"
component={Dashboard}
isAuthenticated={isAuthenticated}
/>
<Route path="/" component={HomePage} />
</Switch>
</Router>
);
}
export default App;
How it works:
- The
PrivateRoute
checks theisAuthenticated
prop. - If the user is authenticated, it renders the requested component.
- If not, it redirects to the login page.
This is a basic example, but you can extend the logic to handle roles or other conditions.
Top comments (0)