LoginSignup
6
2

More than 1 year has passed since last update.

react-router-dom でページ遷移できない原因

Last updated at Posted at 2021-10-21

課題

react-router-dom を使ってサンプルと同じように書いたけれどページ遷移できずに詰まったことはありませんか?

初心者がハマりやすいポイントですが、react-router-dom のルーティングの方法は2種類あります。

ルーターには2種類ある

それぞれの方法でURLが変わります。
HashRouter を使っていた場合、URL に #(ハッシュ) が追加されるので、 https://example.com/about のようにアクセスすると / にリダイレクトされます。

解決方法

まず、自分が使っているのが HashRouterBrowserRouter を確かめて下さい。

  • HashRouterhttps://example.com/#/about
  • BrowserRouterhttps://example.com/about

正しい形式の URL でアクセスすると無事にページ遷移されるハズです。

HashRouter

  • メリットはサーバーサイドでの設定が不要。
  • デメリットはURL の形式がいつもと違うので、ユーザーが使いづらいケースが出てくる?

URLの形式

https://example.com/#/
https://example.com/#/about

import { HashRouter, Route } from "react-router-dom";

return (
  <HashRouter>
    <Route exact path="/">component={HOME}</Route>
    <Route exact path="/about" component={AboutUs} />
  </HashRouter>
)

BrowserRouter

  • メリットはURLの形式がいつもと同じなので、ユーザーが違和感なく使える。
  • デメリット
    • サーバサイドの設定が必要。(後述)
    • サーバーサイドでどの URL にアクセスされているか判別できない。

URLの形式

https://example.com/
https://example.com/about

import { BrowserRouter } from 'react-router-dom';

return (
  <BrowserRouter>
    <Route exact path="/">component={HOME}</Route>
    <Route exact path="/about" component={AboutUs} />
  </BrowserRouter>
)

BrowserRouter を使う場合は、全てのアクセスを index.html にリダイレクトする設定をサーバーサイドでする必要があります。

具体的には、create-react-appで言うと、 public ディレクトリに、 _redirects というファイルを作成し以下のように書きます。

/*    /index.html   200
6
2
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
6
2