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でルーティング設定を理解する

0
Last updated at Posted at 2026-02-15

はじめに

React のルーティングについて学ぶ機会があったので、備忘録として記載します。

今回解説するコード

import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { Today } from './pages/Today'
import { AddExercise } from './pages/AddExercise'
import './App.css'

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Today />} />
        <Route path="/add" element={<AddExercise />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Router>
  )
}

export default App

そもそも「ルーティング」とは?

「URLに応じて表示する画面を切り替える仕組み」

通常のWebサイトではページ遷移するとリロードが発生しますが、
Reactでは SPA という仕組みで、
ページをリロードせずに画面を切り替えます。

使用しているライブラリ

今回使用しているのは

React Router

Reactでルーティングを実装するための代表的なライブラリです。


コード解説

import

import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
  • BrowserRouter

    BrowserRouter as Router
    

    ただの別名定義
    長いから短くしてるだけ。

  • Routes
    複数のRouteをまとめる「入れ物」

  • Route
    「URLとコンポーネントの対応表」

ルーティング本体

<Router>
  <Routes>
    <Route path="/" element={<Today />} />
    <Route path="/add" element={<AddExercise />} />
    <Route path="*" element={<Navigate to="/" replace />} />
  </Routes>
</Router>
  • <Router>
    アプリ全体を包む。
    これがないとルーティングは機能しない。

  • <Route path="/" element={} />
    「URLが / のとき Todayコンポーネントを表示」
    → Today表示

  • <Route path="*" element={<Navigate to="/" replace />} />
    * は「どのパスにも一致しなかった場合」
     

  • <Navigate to="/" replace />
    で 「/」に強制リダイレクトされる。

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?