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?

【React】Outlet に context を渡す方法

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

実は <Outlet />context として値を渡せること、知っていますか?

私は最近まで知らなくて、子コンポーネントごとに グローバルステートを呼び出していました
でも Outlet を使えば、親レイアウトから子ルートにスマートに値を渡せます。

今回はその方法をシンプルにまとめてみます。


親コンポーネント(渡す側)

// 親コンポーネント
import { Outlet } from "react-router-dom";

export function Layout() {
  const user = { role: "student" };

  return (
    <div>
      <h1>共通レイアウト</h1>
      {/* ここで context を渡す */}
      <Outlet context={{ role: user.role }} />
    </div>
  );
}

子コンポーネント(受け取る側)

子では useOutletContext フックを使います。
型をつけておくと TypeScript 的にも安心です。

import { useOutletContext } from "react-router-dom";

type ContextType = {
  role: string;
};

export function StudentPage() {
  const { role } = useOutletContext<ContextType>();

  return <div>Role: {role}</div>;
}

まとめ

  • 親 → <Outlet context={{ 任意の値 }} />
  • 子 → useOutletContext<型>() で受け取れる
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?