1
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?

Tanstack RouterでURLのパラメータを受け取る方法

Posted at

createFileRoutevalidateSearch オプションに関数を指定することで、URLの検索パラメータを検証し、安全に型付けされた状態でコンポーネントに渡すことができる。

下記は、name という検索パラメータを受け取る例。

import { createFileRoute } from '@tanstack/react-router'

// URLに `?name=...` が含まれる場合を想定
export const Route = createFileRoute('/')({
  // search パラメータを検証し、コンポーネントに渡す値を返す
  validateSearch: (search: { name?: string }) => {
    // デフォルト値を設定
    return { name: search.name || 'Guest' } 
  },
  component: App,
});

function App() {
  // validateSearch で検証・変換された値を取得
  const { name } = Route.useSearch();

  return <div>Hello, {name}!</div>
}

また、validateSearchに指定する関数はzodなどのバリデーションライブラリを使用することも可能。

参考

1
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
1
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?