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 Router v6 ルーティング設定 2024年版

Posted at

はじめに

どうも!フリーエンジニアKeiです🐈

Reactでルーティング設定をしたい!
⇒調べるけど、詳しく書いてあるから逆に理解しにくい!

という問題にぶち当たったので初学者に分かるように簡単にまとめました。
(あくまで概要的な内容なので、もっと詳しく知りたい方は各々ググってくだちい)

今は、
Vite+React,tailwindcss,node.js.mongoDB
でwebサイト作成をしています。

問題

・ルーティングってなにそれ?簡単にルーティングを理解
・実際どうやるの!⇒解決方法

簡単にルーティングを理解

任意のコンポーネント(別のページとか)を紐づけできる仕組み
React単体では複雑な紐づけができないのでReact Router(ルーティングの仕組み)が存在している。
要は、「メインのページからAに飛ばしたり、Bに飛ばしたり、AからCのページに飛ばしたり、メインに戻ったりしたい!どうしたらいいんだろう・・・」と思ったら使えるという認識でいい。

解決方法

react-routeライブラリをインストール
それぞれにルーティングの設定をしていく

ライブラリのインストール

※Reactがインストールされている前提の話となります。
プロジェクトを立ち上げたディレクトリのターミナルで次のコマンドでインストール

npm install react-router-dom

インストールが終わったらディレクトリのpackage.jsonファイルで動作確認を行ったライブラリのバージョンを確認しておきます。

package.json
{
    "express": "^4.19.2",
    "mongoose": "^8.4.0",
    "nodemon": "^3.1.1",
    "react": "^18.2.0",
    "react-anchor-link-smooth-scroll": "^1.0.12",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.23.1"
  },
//上記抜粋した内容

ターミナルで起動します。

npm run dev

これをやる

今回はヘッダーで好きなところに遷移させる設定とします。
(Link設定を使います)
Header⇒Home Header⇒About

用意したもの(今回用)

src配下にcomponentsディレクトリを作成。
さらにcomponents配下にPagesとHeadercomponentsディレクトリを作成。
それぞれにHomePage,About,nomatch,Header(紐づけしたいjsx)を作成した。

src/components/Pages/HomePage.jsx
src/components/Pages/About.jsx
src/components/Pages/nomatch.jsx
src/components/Headercomponents/Header.jsx

次の順番で記載していきます。

①App.jsx
②main.jsx
③Header.jsx
④紐づけしたい.jsx

①App.jsx

App.jsx
import { Routes, Route, Link } from "react-router-dom";
import Home from "./components/Pages/HomePage";
import About from "./components/Pages/About";
import Header from "./components/Headercomponents/Header";
import NoMatch from "./components/Pages/nomatch";

function App() {
  return (
    <div className="App">
      <Header />

      <div>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/About" element={<About />} />
          <Route path="*" element={<NoMatch />} />
        </Routes>
      </div>
    </div>
  );
};
export default App;

②main.jsx

main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css"; //これはtailwindcss関連
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

③Header.jsx

※classNameの中身は好きなように記入する(tailwindcss関連を調べてください)

Header.jsx
import React from "react";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";

const Header = () => {
  const navigate = useNavigate();

  return (
  <>
   {/**ヘッダー */}
      <header className="">
        <div className="">
        
          {/**ロゴ部分 */}
          <Link to="/" className="">
            <span className="">ロゴとか</span>
          </Link>

          {/**ナビゲーション部分 */}
          <nav className="">
            <Link to="/" className="">
              Home
            </Link>

            <Link to="/About" className="">
              About
            </Link>
            
          </nav>
        </div>
      </header>

  </>
  );
};

export default Header;

④紐づけしたい.jsx

HomePage,About,nomatchを記載

HomePage.jsx
import React from "react";

const HomePage = () => {
  return (
     <h1>HomePageのページです</h1>;
  );
};

export default HomePage;
About:jsx
import React from "react";

const About = () => {
  return (
     <h1>Aboutのページです</h1>;
  );
};

export default About;
nomatch:jsx
import React from "react";

const nomatch = () => {
  return (
     <h1>このページは調整中です</h1>;
  );
};

export default nomatch;

あとは、localhostで実際に画面が遷移するか確認してみよう!

おわりに

私自身もそうですが、初学者だからこそ色んな仕組みをふわっとした理解で実装していくことになると思います。
ごちゃつきすぎて理解が難しくなり設定を間違えていたり、タイプミスとかでつながらない場合もありますので、
「出来ないぞ…」と煮詰まった時は、一度新しいプロジェクトを立ち上げ直して、ルーティングだけ設定してみると理解がしやすいかと思います。特に初学者は、環境構築の理解にもつながるのでおすすめしておきます。

参考

React Router v6 はじめでもわかるルーティングの設定方法の基礎
https://reffect.co.jp/react/react-router-6

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?