Reputation: 827
From my understanding:
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?
Upvotes: 10
Views: 21513
Reputation: 590
React Router examples offer a little bit another way to build routes structure.
let routes: RouteObject[] = [
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <Home /> },
{
path: "/courses",
element: <Courses />,
children: [
{ index: true, element: <CoursesIndex /> },
{ path: "/courses/:id", element: <Course /> },
],
},
{ path: "*", element: <NoMatch /> },
],
},
];
Upvotes: 4
Reputation: 203373
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>
);
}
Upvotes: 33