So I want to have one or possibly more Routes in the future to be protected and only accessible if the user is authenticated, but so far I only have the "/dashboard" route as Protected but I when I run the website nothing gets renders on my pages, only white screen and no errors on the console only this shows up there.
I’ve also tried just swapping the isAuth ternary for a dummy true or false, but I get the same result.
Loading React Element Tree…
If this seems stuck, please follow the troubleshooting instructions.
this is my code:
ProtectedRoute.js
import { Outlet } from 'react-router-dom'
import { AppContext } from '../contexts/AppContext'
import Login from '../pages/Login';
const userAuth = () => {
const {isAuthenticated} = useContext(AppContext);
return isAuthenticated;
}
const ProtectedRoute = () => {
const isAuth = userAuth();
return isAuth ? <Outlet/> : <Login/>
}
export default ProtectedRoute;
App.js
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
import Home from './pages/Home';
import Login from './pages/Login';
import ProtectedRoute from './utils/ProtectedRoute';
function App() {
return (
<Routes>
<Route path='/' element = {<Home/>} />
<Route path='/login' element = {<Login/>} />
<Route element={<ProtectedRoute/>}>
<Route path='/dashboard' element= {<Dashboard/>} />
</Route>
</Routes>
);
}
export default App;
EDIT
I actually do have an error of invalid Syntax.
EDIT2
I simplyfied my code and also implemented Navigate sill syntax error…
caught SyntaxError: Unexpected token ‘<‘ (at ProtectedRoute.js?t=1683234715943:8:28)
ProtectedRoute.js
import React, { useContext } from 'react'
import { Outlet, Navigate } from 'react-router-dom'
import { AppContext } from '../contexts/AppContext'
const ProtectedRoute = () => {
const { isAuthenticated } = useContext(AppContext);
return isAuthenticated ? <Outlet/> : <Navigate to='/login' replace />;
}
export default ProtectedRoute;
2
Answers
as @Drew Reese pointed out all I had to do was to change the file type from ProtectedRoute.js to ProtectedRoute.jsx
Your code need some changes.You need to wrap your component with ProtectedRoute.
ProtectedRoute.js
App.js