banner
rabithua

rabithua

twitter
github

React ルーターとレイアウトの書き方の最適化

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

Old Solution (Using children)#

I will create a separate layout directory and place 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 due to child route navigation.

New Solution (Using Outlet)#

Similarly, I will create a separate layout directory and place 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 routing 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 style, if you use a different style, you can let an AI like ChatGPT help you convert the types.

Then, the <Mine /> page doesn't need any other special code. If you have made changes from the old style, remember to remove the layout referenced in the page.

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

Final Thoughts#

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 blog posts 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 Post: 仰止 - React 路由加布局的写法优化

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。