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?

【画面移行させる方法】

1
Posted at

まずはReactを導入しているディレクトリにて以下のコマンドを実行し、react-router-domのインストールを行う。
今回はディレクトリをバックエンドとフロントエンドで分けてたから、フロント側でインストールをした。

npm install react-router-dom

index.html→index.js→App.js→各ページ→各コンポーネント(ボタンとかフォームとか)っていう感じの流れで今回は作った。
index.jsのところに、BrowserRouterタグでルーティングを設定するコンポーネントをかこってあげる。(ここに書くのが一般的)
こうすることで、複数のページがインポートできた!
これを書いてないときは、ホーム画面、ログイン画面、を一個ずつコメントアウトして作成してた...。

<index.js>

import React from "react";
import App from "./App";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";//インポート文も忘れない!

const root = createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>//これによってApp 内のすべてのページで React Router を使うことが可能になる!
    <App />
  </BrowserRouter>
);

BrowserRouterとは?
普通のWebサイトでは、ページをクリックすると サーバーから新しいページが読み込まれます。 でも、React は 「1枚のページの中で画面を切り替える」 仕組みを使うので、ページ全体をリロードしません。
そこでBrowserRouterを使うと、URL で画面の切り替えができる ようになる。
とりあえず今は、ページを切り替える際に必要って覚えとく!

次に、App.jsのところにRoutes, Routeタグのインポート文を書いて、
サンプルみたいな感じで書き加えた。<Routes>の中に<Route>を入れる
path="/"のようにパスを設定する
element={<Home />}のように表示するコンポーネントを指定する
下の例で行くと、/threadsという URL にアクセスしたら Threads コンポーネントを表示するという意味になる。
もうこんな感じって覚える!

<App.js>

import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Threads from "./pages/Threads";

function App() {
  return (
    <Routes> {/*  Routes を使って画面遷移を管理 */}
        <Route path="/" element={<Home />} />
        <Route path="/threads" element={<Threads />} /> {/* ルートを確認 */}
    </Routes>
  );
}

export default App;

これでホームとかにボタンを置くと、クリックしたらページが移動できるようになる!

<index.jsx>
import { useNavigate } from "react-router-dom";

function NavigateButtons() {
  const navigate = useNavigate();

  return (
    <div>
      <button onClick={() => navigate("/")}>ホームへ</button>
      <button onClick={() => navigate("/threads")}>スレッドへ</button>
    </div>
  );
}
export default NavigateButtons;

Routes とは?
Routesは、React Routerで 「どのURLでどのコンポーネントを表示するか?」 を管理するもの。Routesの中に 複数のRouteを入れることができる のがポイント!

Route とは?
Routeは「特定のURLでこのコンポーネントを表示する」というルールを作るもの。

ちなみにページ移行する方法は2種類あって
window.location.href = "/home"; を使うと ページが完全にリロードされる ためgetUserDateは消えてしまう
useNavigate("/home")なら コンポーネントの状態は維持されたまま遷移できる!

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?