概要
- とりあえず、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 link1
、test link2
それぞれをクリックして、pathname、searchの値が変化することを確認します
メモ
使える場所
<Router>
<Route>
で囲まれた部分で useLocation()
を使用できるようです。そうでない場合は下記のようなエラーが発生します。
useParams()
や useHistory()
も同様です。
TypeError: Cannot read property 'location' of undefined
本来の使い方?
<Route path="/funcname">
のように記述して、パスによって要素を切り替えて利用するのが本来かもしれません。