0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TanStackRouterを用いたルーティングでパスパラメータをコンテキストとして利用する

Posted at

/{$groupId}/topのようにパスパラメータを受け取りコンポーネントを表示するという想定で構築してみます。

GroupPageTop

import { useParams } from "@tanstack/react-router"

const GroupPage = () => {
  const {group } = useParams({strict: false})
  
  return (
    <div>
      <h2>{group} GroupPage</h2>
      <p>Welcome to the {group} top Page!</p>
    </div>
  )
}

export default GroupPage

rooter.tsx

import { createRootRoute, createRoute, createRouter, Outlet } from "@tanstack/react-router";
import Home from "./pages/Home";
import GroupPage from "./pages/GroupPage";

const rootRoute = createRootRoute({
  component: () => (
    <div>
      <h1>My App</h1>
      <nav>
        <a href="/">Home</a> |
        <a href="/teamA/top">Team A</a> |
        <a href="/teamB/top">Team B</a>
      </nav>
      <hr />
      <Outlet />
    </div>
  ),
});

const homeRoute = createRoute({ getParentRoute: () => rootRoute, path: "/", component: Home });

const groupRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: "/$group/top",
  component: GroupPage
})

export const router = createRouter(
  {
    routeTree: rootRoute.addChildren(
      [
        homeRoute, 
        groupRoute
      ]
    ) 
  }
);

Home.tsx

const Home = () => <div><h2>Home</h2><p>Welcome to the homepage!</p></div>;
export default Home;

動作確認

http://localhost:5173/teamA/top
にアクセスします。

image.png

OKですね。
パスパラメータからコンテキストを取得できたので、JotaiContextに代入しておくことで使いまわせます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?