I am in trouble using nested routes in react router v6.
What I have is a component called pizzas where I show a list of pizzas and then when I click in one pizza I want the details to appear. All works fine except that the pizzas details appear in the same component where the list of pizzas are. I what that pizza details to appear without the list.
Little example code:
routes.js
import Sidebar from "./components/Layout/sidebar/Sidebar";
import Pizzas from "./screens/Pizzas/pizzasScreen";
import PizzaDetails from "./screens/PizzaDetails/pizzaDetails";
const routes = [
{
path: "/",
element: <Sidebar />,
children: [
{
path: "/pizzas",
element: <Pizzas/>,
children: [
{ path: ":id",
element: <PizzaDetails />
}
],
},
],
},
];
export default routes;
pizzasScreen.js
import React from "react";
import { Link, Outlet } from "react-router-dom";
const Pizzas = () => {
return (
<div>
<p>Example of pizzas</p>
<Link to="/pizzas/1">
<span>Pizza 1</span>
</Link>
<Outlet />
</div>
);
};
export default Pizzas;
pizzaDetails.js
import React from "react";
import { useParams } from "react-router-dom";
const PizzaDetails = () => {
const { id } = useParams();
return (
<>
<h2>{`Pizza ${id} details`}</h2>
</>
);
};
export default PizzaDetails;
With all that code what I have is the pizza screen where the list appear, well in that case only one:
And then when I click on Pizza 1 I have this:
The thing is, what can I do so pizzasScreen component only renders:
Example of pizzas
Pizza 1
and pizzaDetails only renders:
Pizza 1 details
>Solution :
If I’m understanding correctly that you don’t want the Pizzas component to be a layout component and render the <p>Example of pizzas</p> element and links and the routes, then you can abstract the <p>Example of pizzas</p> element and links into a new component and render that as an index route for "/pizzas". Effectively you move the Outlet up to be the layout component and move Pizzas component down into an index route to be rendered into the Outlet when the path is exactly "/pizzas".
const routes = [
{
path: "/",
element: <Sidebar />,
children: [
{
path: "/pizzas",
element: <Outlet />,
children: [
{
index: true,
element: <Pizzas/>,
},
{ path: ":id",
element: <PizzaDetails />
}
],
},
],
},
];
Pizzas
const Pizzas = () => {
return (
<div>
<p>Example of pizzas</p>
<Link to="/pizzas/1">
<span>Pizza 1</span>
</Link>
</div>
);
};

