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(Vite)の実行フロー

Posted at

はじめに

Reactの勉強を始めたが、ファイルが多く、実行の流れがつかみにくかったのでまとめる。


主要なファイルと役割

index.html

ブラウザで最初に読み込まれるファイル。

  • #root という空の <div> を用意

  • main.tsx(エントリーポイント)を呼び出す

<body>
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
</body>

main.tsx

  • React アプリの「起動スクリプト」

  • #root に ReactDOM をマウント

  • ルーティングやコンテキストプロバイダーをここで設定することが多い

  • main.tsxでルーティング設定する場合もある

import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import { router } from './routes'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
)

<RouterProvider router={router} />

  • react-router-dom v6.4以降で使う ルーターの提供コンポーネント

  • router にルーティング設定をまとめておいて、それをここで全体に渡す

  • アプリ全体が「どのURLでどのコンポーネントを表示するか」を理解できるようになる

src/routes/index.tsx
import { createBrowserRouter } from "react-router-dom";
import Root from "./routes/Root";
import App from "./App";

export const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    children: [
      { path: "app", element: <App /> }
    ]
  }
]);

このコードの場合は"/"にアクセスすると、Root.tsx のコンポーネントを表示する

routes/Root.tsx

  • react-router-dom を使っている場合、ここが「ルートレイアウト」になる

  • 共通の <header><footer> を配置する

  • <Outlet /> を置いて、子ルート(例えば App.tsx)をここに差し込む

import { Outlet } from 'react-router-dom'

export default function Root() {
  return (
    <div>
      <header>共通ヘッダー</header>
      <main>
        <Outlet /> {/* 子ルートがここに描画される */}
      </main>
      <footer>共通フッター</footer>
    </div>
  )
}

App.tsx

  • 実際に描画されるコンポーネント(ページ内容)

  • 通常は Root.tsx の <Outlet /> にマウントされる

App.tsx
export default function App() {
  return <h1>Hello React!</h1>
}
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?