From my understanding:
- <Route loader...> "only works if using a data router"
- 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?
CodePudding user response:
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>
);
}