Reputation: 121
I am building a small react app, and I have implemented my routes like this:
import React, { lazy } from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
const App = lazy(() => import("./App"));
const Home = lazy(() => import("./Pages/Home"));
const Registro = lazy(() => import("./Pages/Dashboard"));
const Summary = lazy(() => import("./Pages/Summary"));
const Inventario = lazy(() => import("./Pages/Inventario"));
const Estadisticas = lazy(() => import("./Pages/Estadisticas"));
const Dashboard = lazy(() => import("./Pages/Dashboard"));
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="dashboard" element={<Dashboard />}>
<Route index element={<Summary />} />
<Route path="estadisticas" element={<Estadisticas />} />
<Route path="inventario" element={<Inventario />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
</React.StrictMode>
);
As you can see I got some nested routes inside my Dashboard component, where I have set the Summary component to match by default using the index prop. My dashboard component is something like this:
import { Outlet, Link } from "react-router-dom";
export default function Dashboard() {
return (
<div>
<nav>
<ul>
<li><Link to="/">Summary</Link></li>
<li><Link to="estadisticas">Estadisticas</Link></li>
<li><Link to="inventario">Inventario</Link></li>
</ul>
</nav>
<Outlet/>
</div>
);
}
My problem comes when I try to access the Summary component from Link to="/" making use of the nav, instead of rendering the Summary component, it renders the Home component. I have also tried with Link to="dashboard", but the url ends up being something like dashboard/dashboard, which does not work. is there any way to access the Summary component from using Link to?
Upvotes: 3
Views: 289
Reputation: 202979
The issue is that paths that start with a "/"
character are considered to be absolute paths. This is why the "summary" link is linking all the way back to "/"
instead of the parent path "/dashboard"
.
You can use "."
as the target to the parent path, "/dashboard"
in the case of user being on "/dashboard/estadisticas"
or "/dashboard/inventario"
paths.
Example:
function Dashboard() {
return (
<div>
<nav>
<ul>
<li>
<Link to=".">Summary</Link>
</li>
<li>
<Link to="estadisticas">Estadisticas</Link>
</li>
<li>
<Link to="inventario">Inventario</Link>
</li>
</ul>
</nav>
<Outlet />
</div>
);
}
Sorry, at this point I'm unable to locate in the official docs this functionality, though there is a brief blurb regarding the use of ".."
to "remove one segment of the parent path". ".."
serves a similar purpose as "."
. Note that ".."
would be used if it was one of Estadisticas
or Inventario
rendering a link to "go up a level".
Upvotes: 2