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?

【React Router】App.jsx(tsx)をルートに設定すると全ページにAppコンポーネントが反映されてしまう

Posted at

はじめに

今までのアプリ作成ではルートディレクトリのコードはApp.tsx(jsx)コンポーネントに記載していました。
ですが、React Routerでルーティングを行った際に同様の方法でコードを記述したところ、全てのページにApp.tsxのコンポーネント内容が反映されていました。

原因のコード

App.tsx
import "./App.css";
import { BrowserRouter } from "react-router";
import { Router } from "./routing/Router";
import { Button } from "@chakra-ui/react";

export default function App() {
  return (
    <>
      <BrowserRouter>
        <Button>サンプル</Button>
        <Router />
      </BrowserRouter>
    </>
  );
}

上記で配置したButtonコンポーネントがルーティング先のコンポーネントでも表示されてしまっていました。

対処法

Home画面のようにルートパスに適用したいコンポーネントは<App>ではなくホーム画面用のコンポーネントを別途用意する。
具体的には<Home>コンポーネントなど。

また、ルーティングするためのコンポーネント内で上記で設定した<Home>コンポーネントをルートパスに設定する。

Home.tsx
import { Button } from "@chakra-ui/react";

export default function Home() {
  return (
    <>
        <Button>サンプル</Button>
    </>
  );
}
Router.tsx
import { Route, Routes } from "react-router";
import { Register } from "../register";
import { Home } from "../Home";

export function Router() {
  return (
    <>
      <Routes>
        {/* Homeコンポーネントをルートディレクトリに設定 */}
        <Route path="/" element={<Home />} /> 
        <Route path="/cards" element={<Cards />} />
        <Route path="/cards/register" element={<Register />} />
        <Route path="/cards/:id" element={<IdPage />} />
      </Routes>
    </>
  );
}

上記のようにルーティングを設定することでホームディレクトリに特定のコンポーネントのみを表示できる。

最後に

ルーティングの基礎が理解できておらずかなり初歩の部分で詰まってしまいました...
皆さんは同じようにハマった際は上記のことを意識してすぐに対処してみてください。

参考資料

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?