7
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 5 years have passed since last update.

ReactRouter v4 でpathに変数と正規表現を用いる方法

Last updated at Posted at 2020-02-03

<BrowserRouter>
  <Switch>
    <Route path={`${hoge}/fuga/:id(\d+)`} component={MyComponent} />
  </Switch>
</BrowserRouter>

ReactRouterでpathに変数と正規表現を用いたい時、
上のように、テンプレートリテラル(文字列の中に変数を含める書き方)を用いて、
pathに変数を含め、正規表現のチェック(:idが整数である)を行おうとしてもうまく行かない現象でハマりました。

原因

JavaScriptのテンプレートリテラルではバックスラッシュをそのままでは扱えない(エスケープする必要がある)

解決策


<Route path={`${hoge}/fuga/:id(\\d+)`} component={MyComponent} />

バックスラッシュを2個にしてあげると、うまく動作します。

参考URL: https://stackoverflow.com/questions/43067371/react-router-v4-regex-dont-like-template-literals

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