Here is my app.jsx
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import OTAndTOGateKeeper from "./components/otAndTO/OTAndTOGateKeeper.jsx";
import LoginForm from "./components/otAndTO/LoginForm.jsx";
return (
<Router>
<Routes>
<Route path='/otAndTO' element={<OTAndTOGateKeeper/>}>
<Route index element={<OTAndTOForm/>}/>
<Route path="login" element={<LoginForm/>}/>
</Route>
</Routes>
</Router>
);
Here is my OTAndTOGateKeeper.jsx
import { Navigate } from 'react-router-dom';
import OTAndTOForm from "./OTAndTOForm.jsx";
export default function OTAndTOGateKeeper(){
let finalComponent;
if (sessionStorage.getItem("accessToken")){
finalComponent=<OTAndTOForm/>
} else {
finalComponent=<Navigate to="/otAndTO/login"/>
}
return finalComponent;
}
When I Browse the ‘/otAndTO’, it should return the login form; unfortunately, there are nothing return.
However, when I change the App.jsx and OTAndTOGateKeeper.jsx as the following:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import OTAndTOGateKeeper from "./components/otAndTO/OTAndTOGateKeeper.jsx";
import LoginForm from "./components/otAndTO/LoginForm.jsx";
return (
<Router>
<Routes>
<Route path='/otAndTO' element={<OTAndTOGateKeeper/>}>
<Route index element={<OTAndTOForm/>}/>
</Route>
<Route path="login" element={<LoginForm/>}/>
</Routes>
</Router>
);
import { Navigate } from 'react-router-dom';
import OTAndTOForm from "./OTAndTOForm.jsx";
export default function OTAndTOGateKeeper(){
let finalComponent;
if (sessionStorage.getItem("accessToken")){
finalComponent=<OTAndTOForm/>
} else {
finalComponent=<Navigate to="/login"/>
}
return finalComponent;
}
It works as expected.
Here is my environment:
"react-dom": "^18.3.1",
"react": "^18.3.1",
"react-router-dom": "^7.0.2"
I am using the vite+react development tools.
Is the only work for the top level URL?