Private Route--------
import { Navigate,useLocation} from "react-router-dom"
function Protecte({auth, children }) {
return auth ? children : <Navigate to="/login" />;
}
export default Protecte
-----------------------------------
App.js---
<Route path="/admin" element={
<Protecte auth={isLoggedIn}>
<Admin />
</Protecte>
}
/>
//WORKS ON react-router-dom v6
//Using Outlet and Navigate
import { Routes, Route, Outlet, Navigate} from "react-router-dom";
function PrivateOutlet() {
const auth = useAuth();
return auth ? <Outlet /> : <Navigate to="/login" />;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/private-outlet" element={<PrivateOutlet />}>
<Route element={<Private />} />
</Route>
</Routes>
</BrowserRouter>
);
}
const PrivateRoute = ({component: Component, ...rest}) => {
const {isAuthenticated} = rest;
return (
<Route {...rest} render={props => (
isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location}
}}/>
)
)}
/>
);
};
PrivateRoute.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
};
function mapStateToProps(state) {
return {
isAuthenticated: state.user.isAuthenticated,
};
}
export default connect(mapStateToProps)(PrivateRoute);