I’m using React Router v6 and am creating private routes for my application.
In file PrivateRoute.js, I’ve the code
JavaScript
x
12
12
1
import React from 'react';
2
import {Route,Navigate} from "react-router-dom";
3
import {isauth} from 'auth'
4
5
function PrivateRoute({ element, path }) {
6
const authed = isauth() // isauth() returns true or false based on localStorage
7
const ele = authed === true ? element : <Navigate to="/Home" />;
8
return <Route path={path} element={ele} />;
9
}
10
11
export default PrivateRoute
12
And in file route.js I’ve written as:
JavaScript
1
4
1
2
<PrivateRoute exact path="/" element={<Dashboard/>}/>
3
<Route exact path="/home" element={<Home/>}/>
4
I’ve gone through the same example React-router Auth Example – StackBlitz, file App.tsx
Is there something I’m missing?
Advertisement
Answer
I ran into the same issue today and came up with the following solution based on this very helpful article by Andrew Luca
In PrivateRoute.js:
JavaScript
1
11
11
1
import React from 'react';
2
import { Navigate, Outlet } from 'react-router-dom';
3
4
const PrivateRoute = () => {
5
const auth = null; // determine if authorized, from context or however you're doing it
6
7
// If authorized, return an outlet that will render child elements
8
// If not, return element that will navigate to login page
9
return auth ? <Outlet /> : <Navigate to="/login" />;
10
}
11
In App.js (I’ve left in some other pages as examples):
JavaScript
1
27
27
1
import './App.css';
2
import React, {Fragment} from 'react';
3
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
4
import Navbar from './components/layout/Navbar';
5
import Home from './components/pages/Home';
6
import Register from './components/auth/Register'
7
import Login from './components/auth/Login';
8
import PrivateRoute from './components/routing/PrivateRoute';
9
10
const App = () => {
11
return (
12
<Router>
13
<Fragment>
14
<Navbar/>
15
<Routes>
16
<Route exact path='/' element={<PrivateRoute/>}>
17
<Route exact path='/' element={<Home/>}/>
18
</Route>
19
<Route exact path='/register' element={<Register/>}/>
20
<Route exact path='/login' element={<Login/>}/>
21
</Routes>
22
</Fragment>
23
</Router>
24
25
);
26
}
27
In the above routing, this is the private route:
JavaScript
1
4
1
<Route exact path='/' element={<PrivateRoute/>}>
2
<Route exact path='/' element={<Home/>}/>
3
</Route>
4
If authorization is successful, the element will show. Otherwise, it will navigate to the login page.