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>
}
/>
import React from 'react'
import { Redirect, Route } from 'react-router-dom'
const Protected = ({ component, ...rest }) => {
<Route
{...rest}
render={() => {
localStorage.getItem('login') ? (
<component {...props} />
) : (
<Redirect to='/login' />
)
}}
/>
};
export default Protected
// app.js
import Protected from'./components/Protected'
<Router>
<Protected exact path="/"component={Home}/>
<Protected exact path="/about"component={About}/>
<Protected exact path="/contact"component={Contact}/>
</Router>
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoutes = () => {
const location = useLocation();
const { authLogin } = useContext(globalC);
console.log("authLogin", authLogin);
return authLogin
? <Outlet />
: <Navigate to="/login" replace state={{ from: location }} />;
}
<BrowserRouter>
<Routes>
<Route path="/" element={<PrivateRoutes />} >
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/about" element={<About />} />
</Route>
<Route path="/login" element={<Login />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
</BrowserRouter>