3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React Routerでlocationを取得するサンプル

Last updated at Posted at 2021-07-28

概要

  • とりあえず、window.location.pathname,searchを取得したい
    • とりあえず window.location.pathname を記述しても取得は可能
    • だが、きっとスマートな方法があるに違いないと思っている
  • 2021年時点でのReact初学者
  • 調べると、どうやらReactは歴史があり、時期によって推奨される記述方法やモジュールが変遷しているように感じている

(いつか古くなると思いつつ)一応取得できたので、メモしておこうと思います。

手順

実行環境

  • Windows10 + WSL2 + Ubuntu 20.04 + Node.js 16
$ cat /etc/issue
Ubuntu 20.04.2 LTS \n \l
$ node --version
v16.5.0

準備

Reactアプリケーション router-sample を作成し、React Routerモジュールをインストールします

$ npm install -g create-react-app
$ npx create-react-app router-sample
$ cd router-sample
$ npm install react-router-dom

モジュール類のバージョン確認

$ npm list
router-sample@0.1.0 (snip)../router-sample
├── @testing-library/jest-dom@5.14.1
├── @testing-library/react@11.2.7
├── @testing-library/user-event@12.8.3
├── bindings@1.5.0 extraneous
├── file-uri-to-path@1.0.0 extraneous
├── nan@2.14.2 extraneous
├── react-dom@17.0.2
├── react-router-dom@5.2.0
├── react-scripts@4.0.3
├── react@17.0.2
└── web-vitals@1.1.2

サンプルソース

src/App.js
import React from "react";
import {
  BrowserRouter as Router,
  Route,
  useLocation
} from "react-router-dom";

export default function App() {
  return (
    <Router>
      <Route>
        <Sample />
      </Route>
    </Router>
  );
}

function Sample() {
  const {
    pathname,
    search
  } = useLocation();
  return (
    <>
      <p><a href="/test/link?a=1&b=2">test link1</a></p>
      <p><a href="/go/?a=xyz">test link2</a></p>
      <p>location.pathname:{pathname}</p>
      <p>location.search:{search}</p>
      <p>window.location.pathname:{window.location.pathname}</p>
      <p>window.location.search:{window.location.search}</p>
    </>
  )
}

実行

$ npm start

Webブラウザで確認します

  • test link1test link2 それぞれをクリックして、pathname、searchの値が変化することを確認します

kakunin

メモ

使える場所

<Router> <Route> で囲まれた部分で useLocation() を使用できるようです。そうでない場合は下記のようなエラーが発生します。
useParams()useHistory() も同様です。

TypeError: Cannot read property 'location' of undefined

本来の使い方?

<Route path="/funcname"> のように記述して、パスによって要素を切り替えて利用するのが本来かもしれません。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?