I am doing a practice exercise and I am creating sub-routes with react router dom v6, the problem I have is that the profile route has an authentication if it is authenticated it shows me the profile component otherwise it sends me to home, now to this /profile route I created a /exerciselist subroute but when I want to access /profile/exerciselist the component does not load me, it sends me directly to the /profile route, how can I make it load the profile/exerciselist route?
import React from 'react'
import { BrowserRouter, Route, Routes, Navigate} from "react-router-dom"
import { useContext } from "react"
import { authContext } from "./context/authContext"
import Homepage from "./pages/Homepage"
import Login from "./pages/Login"
import Register from "./pages/Register"
import Notfound from "./pages/Notfound"
import Profile from "./pages/Profile"
import Footer from "./components/footer"
import ExercisesList from './components/exercises_list'
import "./public/css/appStyles/appStyles.css"
function App() {
const { auth } = useContext(authContext)
return (
<BrowserRouter>
<Routes>
<Route path="/" element={!auth.auth ? <Homepage/> : <Navigate to="/profile" replace />}/>
<Route path="/register" element={ !auth.auth ? <Register/> : <Navigate to="/profile" replace />}/>
<Route path="/login" element={ !auth.auth ? <Login /> : <Navigate to="/profile" replace /> } />
<Route path="/profile/*" element={ auth.auth ? <Profile /> : <Navigate to="/" replace /> } >
<Route path="exerciselist" element={<ExercisesList/>} />
</Route>
<Route path="*" element={<Notfound/>}/>
</Routes>
<Footer/>
</BrowserRouter>
);
}
export default App;
When rendering nested routes you have a couple options.
Render an Outlet
component in the parent route's component for the nested Route
components to be rendered into.
Example:
import { Outlet } from 'react-router-dom'; ... const Profile = () => {... return ( <>... Profile component JSX... <Outlet /> </> ); };
Remove the trailing "*"
since the nested route is rendered into Outlet
.
<Route path="/profile" element={ auth.auth? <Profile />: <Navigate to="/" replace />} > <Route path="exerciselist" element={<ExercisesList/>} /> </Route>
Render a Routes
and nested Route
components directly in the routed component.
import { Routes, Route } from 'react-router-dom'; ... const Profile = () => {... return ( <>... Profile component JSX... <Routes> <Route path="exerciselist" element={<ExercisesList/>} /> </Routes> </> ); };
...
<Route path="/profile/*" // <-- trailing * allows matching nested routes element={ auth.auth? <Profile />: <Navigate to="/" replace />} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.