Added: protected routing
This commit is contained in:
27
src/App.js
27
src/App.js
@@ -1,15 +1,34 @@
|
|||||||
|
import { Routes, Route, useLocation, Navigate } from 'react-router-dom';
|
||||||
|
|
||||||
import Test from './components/Test';
|
import Test from './components/Test';
|
||||||
import AuthProvider from './config/authProvider';
|
import AuthProvider, { useAuth } from './config/authProvider';
|
||||||
import localizationInit from './config/localization';
|
import localizationInit from './config/localization';
|
||||||
|
|
||||||
localizationInit();
|
localizationInit();
|
||||||
|
|
||||||
|
function RequireAuth({ children }) {
|
||||||
|
let auth = useAuth();
|
||||||
|
let location = useLocation();
|
||||||
|
|
||||||
|
if (!auth.user) {
|
||||||
|
// Redirect them to the /login page, but save the current location they were
|
||||||
|
// trying to go to when they were redirected. This allows us to send them
|
||||||
|
// along to that page after they login, which is a nicer user experience
|
||||||
|
// than dropping them off on the home page.
|
||||||
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<div className="App">
|
<Routes>
|
||||||
<Test />
|
<Route path="/" element={<>Hey there</>} />
|
||||||
</div>
|
<Route path="/login" element={<Test />} />
|
||||||
|
<Route path="/dashboard" element={<RequireAuth>This is secret</RequireAuth>} />
|
||||||
|
</Routes>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom';
|
|||||||
|
|
||||||
import './index.css';
|
import './index.css';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
|
import { BrowserRouter } from 'react-router-dom';
|
||||||
|
|
||||||
const loadingScreen = (
|
const loadingScreen = (
|
||||||
<div
|
<div
|
||||||
@@ -21,7 +22,9 @@ const loadingScreen = (
|
|||||||
ReactDOM.render(
|
ReactDOM.render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<Suspense fallback={loadingScreen}>
|
<Suspense fallback={loadingScreen}>
|
||||||
<App />
|
<BrowserRouter>
|
||||||
|
<App />
|
||||||
|
</BrowserRouter>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
document.getElementById('root')
|
document.getElementById('root')
|
||||||
|
|||||||
Reference in New Issue
Block a user