1
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】現在のページのURLのparamsを参照できるuseParamsをざっくり紹介【React】

Posted at

useParams

URLからparamsを受け取って、値を取得することは多々あると思います。

今回はそんな場面で使えるuseParamsをご紹介します。

いくつか方法があるかと思いますが、一番シンプルに値を取得できるやり方なのではないでしょうか。

実装方法

こちらがuseParamsの実装例です。公式ドキュメントよりお借りしました。

useParamsをインポートし、ファクション内で、変数に代入して、そのparamsの値を文字列に入れて表示させるといったものになっています。

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return <div>Now showing post {slug}</div>;
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
);

参考

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