In my application I am using BrowserRouter
component to render my routes or components . But I want to use loader functionality. but my current approach I am not able to use that feature.
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
As suggested by below link I need to use createBrowserRouter
function .
why loader function not called in react js?
https://reactrouter.com/en/main/routers/picking-a-router
current way of routing.
export default function AppRoutes() {
return (
<Layout>
<Routes>
<Route element={<RequireAuth />}>
<Route
path={'/'}
element={
<React.Suspense
fallback={<div>loading</div>}
children={<Booking />}
/>
}
></Route>
</Route>
<Route element={<RequireAuth />}>
<Route
path={'/app'}
element={
<React.Suspense
fallback={<div>loading</div>}
children={<App />}
/>
}
></Route>
</Route>
</Routes>
</Layout>
);
}
now I am trying to refactor my routing using createBrowserRouter .. I tried like this
const router = createBrowserRouter([
{
path: '/',
loader: () => {
console.log('0000');
return 'ss';
},
element: <RequireAuth />,
},
{
path: '/app',
loader: () => {
console.log('0000');
return 'ss';
},
element: <RequireAuth />,
},
]);
how to render component (Booking and App component). how I will render children in createBrowserRouter approach any idea ??
2
Answers
To render children to any path you do this: Using Booking app as example child
You can find very illustrative examples on their documentation here https://reactrouter.com/en/main/start/tutorial
The
createBrowserRouter
function takes an array ofRouteObject
typesThe
children
property takes another array ofRouteObject
objects, so you can use this recursive structure to build up your routing hierarchy.To convert the first code snippet using the
BrowserRouter
to the new Data Router syntax I suggest the following refactor that:Converts
Layout
to a layout route componentLayout.tsx
Renders a single layout route rendering
RequireAuth
, this makes for code that is a bit more DRYRenders
Booking
andApp
on nested routes under the auth layout routeroutes.tsx
Update main.tsx to render a
RouterProvider
and the computedrouter
instead of theBrowserRouter
componentmain.tsx