Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  178] [ 6]  / answers: 1 / hits: 6394  / 2 Years ago, sun, october 23, 2022, 12:00:00

From my understanding:



  1. <Route loader...> "only works if using a data router"

  2. data routers (like createBrowserRouter) don't allow for wrapping 'all' of the routes in jsx containing <Link> components. See examples


Example: Non data routers


<Router>
<header>
<Link to="/">Home</Link>
</header>
<Routes>
<Route...>
<Route...>
</Routes>
</Router>


Example: data routers (throws error) full example


const router = createBrowserRouter([....]);
<div>
<header>
<Link to="/">Home</Link>
</header>
<RouterProvider router={router} />
</div>

My question is this: How can we create a template that wraps the RouterProvider (and all the content it imports) with a template that makes use of <Link> functionality?


More From » reactjs

 Answers
3

Render the header/Navbar component as part of the routing configuration. In this case you'll create a layout route that renders the header and navbar, and an Outlet for nested routes to render their content into.


Example:


export const Navbar = () => {
return (
<div>
<Link to='/'>Home</Link>
<Link to='/foo'>Foo</Link>
<Link to='/bar'>Bar</Link>
</div>
);
};

...


import {
createBrowserRouter,
RouterProvider,
Outlet
} from 'react-router-dom';

const HeaderLayout = () => (
<>
<header>
<Navbar />
</header>
<Outlet />
</>
);

const router = createBrowserRouter([
{
element: <HeaderLayout />,
children: [
{
path: "/",
element: <div>Hello</div>,
},
{
path: '/foo',
element: <div>foo</div>,
},
{
path: '/bar',
element: <div>foo</div>,
}
],
},
]);

export function App(props) {
return (
<div className='App'>
<RouterProvider router={router} />
</div>
);
}

[#19] Monday, August 1, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daphnew

Total Points: 716
Total Questions: 113
Total Answers: 113

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
daphnew questions
Tue, Nov 3, 20, 00:00, 4 Years ago
Fri, Sep 4, 20, 00:00, 4 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
;