2
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?

More than 3 years have passed since last update.

react-router-domのプロパティ"exact"とは?

Last updated at Posted at 2020-08-24

本記事を書いた経緯

Webアプリを開発するにあたって,ルーティングのためにreact-router-domを利用しました.
その中でも,プロパティのうちの一つであるexactがどのような役割なのか曖昧なまま利用していたのでこちらにまとめます.(Homeのpathに指定するものだと思い込んでいた...)

exactとは?

React Router<Route />内にexact(bool)を記述すると指定したpathとlocation.pathnameが「完全一致」した場合のみコンポーネントを返します.

ドキュメントの例をお借りすると,

path location.pathname exact maches?
/one one/two true no
/one one/two false yes

のようになります.
上の例では,exact=trueのため,完全一致でなければならずmachしません.
一方,下の例では,exact=falseのため,部分一致するone/twoとmachします.

Homeexactを指定する理由

私は,Homeで表示されるページにexactを指定すると勘違いしていましたが,上記のことを踏まえるとあながち間違えではないことが分かります.
つまり,

<Route exact path="/" component={Home} />

のようにexactを指定してあげないと.すべてのlocation.pathについてHomeのpathと部分一致してしまうからです.

参考

react-router

2
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
2
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?