4
0

More than 3 years have passed since last update.

【react-router-dom】ページ遷移させるときに使うuseHistoryをざっくり紹介【React】

Last updated at Posted at 2021-07-18

useHistory

ReactでSPA開発をする際に、eact-router-domでルーティングを設定する場合があると思います。

その際に、Linkだけでなく、ボタンをクリック時の諸々の処理後で画面の遷移をしたい場面が出てくると思います。

そんなときに使うのが、useHistoryです。

実装方法

useHistoryは以下のように、
1.useHistoryを変数を代入
2.使用したい箇所で、pushメソッドで引数にURLを指定する
といったシンプルな手順で実装できます

以下の例は、公式ドキュメントよりお借りしました。
こちらではボタンをクリックすると、/homeへ画面が遷移するようになっています。

useHistory
import { useHistory } from "react-router-dom";

function HomeButton() {
  //1.historyにuseHistoryを代入する
  let history = useHistory();

  //2.使いたい箇所でpushメソッドにURLを指定して、使用する
  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

4
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
4
0