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

useHistoryを使うとエラーになる

0
Last updated at Posted at 2026-04-25

はじめに

udemyの学習でuseHistoryを使おうとしたところエラーが出たので記録しておきます。

問題

useHistoryを使うと出てきたエラーです。
エラー 
(0 , _reactRouterDom.useHistory) is not a function
image.png

解決方法

React17→React18になった影響でuseHistoryは廃止されてしまいました。
なのでhistory.pushやhistory.replace等は全て使えません。
useNavigationまたはuseLocationを使用しましょう

import {  useHistory } from "react-router-dom";
export const Page1 = () => {

  const history = useHistory();
  const onClickDetailA = () => {
    history.push("/page1/detailA");
  };

これを下記の通り変更しました。

import {  useNavigate } from "react-router-dom";
export const Page1 = () => {
  const navigation = useNavigate();
  const onClickDetailA = () => {
  navigation("/page1/detailA");
};

おまけ

次の課題に戻るボタンもあったので記載しておきます。
historyではhistory.goBack()ですが
Navigateでは(-1)で戻ることができるようです。

navigate(-1);  // 1つ前のページに戻る(ブラウザの「戻る」と同じ)
navigate(1);   // 1つ先のページに進む(ブラウザの「進む」と同じ)
navigate(-2);  // 2つ前のページに戻る

おわりに

アップデートされてコードをより短く書けることはいいですね!

参考

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