banner
rabithua

rabithua

twitter
github

Optimizing the Writing of React Router with Layout

This post is only provided as a reference for ideas, ignoring the import part of the code. It may be a bit difficult for React beginners to understand.

Old Solution (Using children)#

I will create a separate layout directory and put my layoutDashboard.tsx file in it. It looks something like this:

function LayoutDashboadrd({ children }: any) {
  return <div>{children}</div>;
}

Then I will use the layout in the code of each page that needs it:

function page() {
  return (
    <LayoutDashboard>
      <div>page content</div>
    </LayoutDashboard>
  );
}

This method is more intuitive, but it has some issues:

  • Each page that needs the layout has to import it separately.
  • The layout in each page is rendered separately, and the layout state is reset after page navigation.

Obviously, this method is not suitable. Is there a better way?
Yes, that is to use layout in the routing, so that all child routes under a path can use the same layout, and the layout state will not be reset when navigating between child routes.

New Solution (Using Outlet)#

Similarly, I will create a separate layout directory and put my layoutDashboard.tsx file in it. It looks something like this:

function LayoutDashboadrd() {
  return (
    <div>
      <Outlet />
    </div>
  );
}

Here, you will notice that children is gone, and instead there is a <Outlet /> in the original position of children.

Then in the original route definition:

export default function GlobalRouterProvider() {
  const router = createBrowserRouter([
    {
      path: "/mine",
      element: <LayoutDashboadrd />,
      children: [
        {
          index: true,
          element: <Mine />,
        },
        {
          path: "filter",
          element: <MineFilter />,
        },
      ],
    },
    {
      path: "*",
      element: <ErrorPage />,
    },
  ]);

  return <RouterProvider router={router} />;
}

I'm used to this routing format, if you use a different format, you can let AI like ChatGPT help you convert the types.

Then, the <Mine /> page does not need any other special code. If you have made changes from the old format, remember to remove the layout referenced in the page.

With this, your React project code is a bit more elegant~

Conclusion#

It's been a while since I wrote a blog post. Actually, I haven't stopped writing, I just write on my own community. The updates are quite frequent, and I feel that the community is a better platform. Writing blogs can be quite stressful, and I don't want to be too superficial.
If you like blogs, you can go to the community and chat~

Original article: 仰止 - React 路由加布局的写法优化

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.