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で状態管理を利用する(jotai)

Posted at

はじめに

前回記事の続きです。Providerを利用せず状態管理のjotaiを利用して作成します。

成果物

スクリーンショット 2023-11-29 11.57.04.png

ソースコード

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);

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?