This post is sequel of my previous post on the routing on react.
Please check that before following this,
"https://dev.to/jmilind1234/all-about-routing-in-react-part-1-ft-react-router-dom-2fd1".
In my previous post I wrote about how to create the routing configuration and difference between server-side-routing and client-side-routing.
Now here, we are going to see about the following topics -
children routes
getting error information in navigation and showing custom error page.
So, let start with children routes. These are also referred as nested routes. Lets, say we have 3 routes as "/", "/about", "/contact" and we want that these 3 pages share same layout, means to say all have same header, footer, sidebar etc.
So, one way is that we create router configuration as we did and on each page we call header, footer and sidebar with page specific component.
This is fine, it will work.
But not smart way. Smart way is to define paths inside children of the "/". Lets see a code example for same.
export const appRouter = new createBrowserRouter([
{
path: "/",
element: <AppLayout />,
errorElement: <Error />,
children: [
{
path: "/",
element: <Body />,
},
{
path: "/about",
element: <About />,
},
{
path: "/contact",
element: <Contact />,
},
{
path: "/restaurant/:resId",
element : <RestaurantMenu/>
}
],
},
]);
Here, for "/" path we have mentioned element, that's basically defines layout for its children routes, errorElement defines what to show if we try to access undefined route. We have also used children prop, that is a place where all nested routes are defined, like for "/" we will show <Body/>
component and similarly for other 3.
But wait, how and where <About/>
will come and layout will be shared.
Well here comes the powerful <Outlet/>
component that comes from react-router-dom package.
const AppLayout = () => {
return (
<div className="app">
<Header />
<Outlet />
</div>
);
};
So, for "/about" path, <Outlet/>
will be replaced by <About/>
and same for rest 3. Here, <Header/>
will be shared by all the children routes.
This was all about nested routes or children routes and how layout is shared and power of <Outlet/>
component.
Now lets begin with custom error page and how to get navigation error information.
First part we already covered while creating routing configuration ( remember - errorElement).
To get the navigation error information, we have a hook "useRouteError", this also comes from "react-router-dom".
In my next post, we will study about query params and route params.
Thanks for reading the post.😊
Top comments (1)
Thanks, for sharing with the community