Reputation: 10772
I have 2 different pages, with different layouts. However, right in the middle of each layout is a common component. I want that component to be rendered into both layouts, without losing state as you navigate between pages.
React router 6 provides the Outlet component, but this accomplishes the opposite effect - it enables you to render different child components within a common layout component. I need to do the opposite - render different layout components, with a common child component wedged into the correct place within the DOM. Take this code for example:
export default function App() {
return (
<BrowserRouter>
<nav>
<NavLink to="layout1" activeClassName="active">
Layout 1
</NavLink>
<NavLink to="layout2" activeClassName="active">
Layout 2
</NavLink>
</nav>
<Routes>
<Route
path="/*"
element={
<div className="glowing">
<Outlet />
</div>
}
>
<Route path="layout1" element={<Layout1Page />} />
<Route path="layout2" element={<Layout2Page />} />
</Route>
</Routes>
</BrowserRouter>
);
}
const Layout1Page = () => (
<main className="layout1-page">
<nav className="left-nav">Some stuff happening on this page</nav>
{/* Need glowing div to be rendered here */}
<aside className="right-bar">Stuff 5</aside>
</main>
);
const Layout2Page = () => (
<main className="layout2-page">
<nav className="left-nav">Layout 2 Here</nav>
{/* Need glowing div to be rendered here */}
</main>
);
I want the .glowing
div to be rendered into both Layout1Page and Layout2Page, right in the place in the DOM as you can see in the comments. Its the surrounding layout that differs between the 2 pages.
My usage of the Outlet
component does what I would like, almost - it renders the .glowing
div in both pages. As you navigate between pages, the .glowing
div is not rerendered, as you can tell because the animation is smooth and does not jump as you navigate. However, its not rendered in the correct place in the DOM, it seems to be tacked on after the Outlet component content is rendered.
How can I organize this, so that a child component is rendered once across 2 routes, into the correct place within the parent component?
Upvotes: 0
Views: 61