1
2

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にルート設定をする

Posted at

Reactにルート設定するための必要な設定をまとめてみました。
react-router-dom v6.28.0

全体像

画面収録 2024-11-18 14.gif

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

npm install react-router-dom

ページの作成

componentsディレクトリを作成し、各ページを作成
分かりやすく、h1タグのみです。

Home.tsx
const Home: React.FC = () => {
  return <h1>HOME</h1>;
};
export default Home;
Before.tsx
const Before: React.FC = () => {
  return <h1>BEFORE</h1>;
};
export default Before;
Next.tsx
const Next: React.FC = () => {
  return <h1>NEXT</h1>;
};
export default Next;
Page404.tsx
const Page404: React.FC = () => {
  return <h1>Not found</h1>;
};
export default Page404;

Navbarコンポーネントの作成

画面遷移用のボタンを配置したコンポーネント

Navbar.tsx
import { Link } from "react-router-dom";

const Navbar: React.FC = () => {
  return (
    <div style={{ display: "flex", justifyContent: "center", gap: "20px" }}>
      <Link className={"link_button"} to="/before">Before</Link>
      <Link className={"link_button"} to="/">Home</Link>
      <Link className={"link_button"} to="/next">Next</Link>
    </div>
  );
};
export default Navbar;

ルート設定のコンポーネントを作成

ルート用のコンポーネントを作っておくと、App.tsxの見通しが良くなる。

AppRoutes.tsx
import { Route, Routes } from "react-router-dom";
import Home from "./Home.tsx";
import Next from "./Next.tsx";
import Before from "./Before.tsx";
import Page404 from "./Page404.tsx";

const AppRoutes: React.FC = () => {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/next" element={<Next />} />
      <Route path="/before" element={<Before />} />
      <Route path="*" element={<Page404 />} />
    </Routes>
  );
};

export default AppRoutes;

path="*" は、どのpathにも一致しない場合にここへ来る。
Not Foundページに使う

App.tsxの設定

App.tsx
import "./App.css";
import Navbar from "./components/Navbar.tsx";
import AppRoutes from "./components/AppRoutes.tsx";

const App = () => {
  return (
    <>
      <h1>react-router-dom</h1>
      <AppRoutes />
      <Navbar />
    </>
  );
};

export default App;

1
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?