LoginSignup
3
2

Reactのページ遷移でuseHistoryが使えない

Posted at

始めに

現在Udemyの講座でReactを学習中です!
今回通常のページ遷移は<Link to〜 を用いてページ遷移するのですが、今回は関数を用いてページ遷移するとのことだったので、useHistoryのフックを使用しました。
しかしv5→v6のバージョンアップが原因でuseHistoryはサポートされていませんでした。
そこでuseNavigateを使用したので解説します!

v5での書き方

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

export const Page1 = () => {
  const history = useHistory();
  const onClickDetailA = () => history.push(`detail1`);

  return (
    <div>
      <h1>Page1です!</h1>
      <button onClick = {onClickDetailA}>detailA</button>
    </div>
  );
};

v6での書き方

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

export const Page1 = () => {
  const navigate = useNavigate();
  const onClickDetailA = () => navigate(`detail1`);
  
  return (
    <div>
      <h1>Page1です!</h1>
      <button onClick = {onClickDetailA}>detailA</button>
    </div>
  );
};

まとめ

今回はuseHistoryではなくuseNavigateで記述する方法をまとめました。
ちなみにuseNavigateでstateを渡すときにはオプション値として渡すそうです!

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

export const Page1 = () => {
  const arr = [...Array(100).keys()];
  const navigate = useNavigate();
  const onClickDetailA = () => {
    navigate(`detail1`, { state: arr });
  };
  return (
    <div>
      <h1>Page1です!</h1>
      <button onClick = {onClickDetailA}>detailA</button>
    </div>
  );
};

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