はじめに
前回記事の続きです。Providerを利用せず状態管理のjotaiを利用して作成します。
成果物
ソースコード
src/App.tsx
import { Content } from "./Content";
import { Header } from "./Header";
import { Provider } from "jotai";
const App: React.FC = () => {
return (
<Provider>
<Header />
<Content />
</Provider>
);
};
export default App;
src/Header.tsx
import { useAtom } from "jotai";
import { activeTabAtom } from "./state";
const TABS = ["Tab1", "Tab2", "Tab3", "Tab4"];
export const Header: React.FC = () => {
const [, setActiveTab] = useAtom(activeTabAtom);
return (
<div>
{TABS.map((tab, index) => (
<button key={index} onClick={() => setActiveTab(index)}>
{tab}
</button>
))}
</div>
);
};
src/Content.tsx
import { useAtom } from "jotai";
import { activeTabAtom } from "./state";
export const Content: React.FC = () => {
const [activeTab] = useAtom(activeTabAtom);
return (
<div>
{activeTab === 0 && <div>Content for Tab 1</div>}
{activeTab === 1 && <div>Content for Tab 2</div>}
{activeTab === 2 && <div>Content for Tab 3</div>}
{activeTab === 3 && <div>Content for Tab 4</div>}
</div>
);
};
src/state.ts
import { atom } from "jotai";
// タブの状態を保持するアトムを定義
export const activeTabAtom = atom(0);