2
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 1 year has passed since last update.

react-router-dom v5⇨v6のhistoryの置換

Posted at

どうも、React初心者です。

先日、UdemyでReactを始めました。
(https://www.udemy.com/course/firebase-react-hookstypescriptweb/)
そこで使用したコードを
なんとなくreact-router-dom v5 ⇨ v6へ移行していたとき、

App.ts(旧)だと、
props.historyで

TypeError: Cannot read properties of undefined (reading 'push')

ってエラー出ました。

  • App.ts(旧)
App.ts
import React, { useState, useEffect } from 'react';
...


const App: React.FC = (props: any) => {
...
  useEffect(()=>{
    const unSub =auth.onAuthStateChanged((user)=>{
      !user && props.history.push("login")
    });
    return () => unSub();
  });
...

  return (
  ...
  );
}

export default App;

エラーはDoc等で解決しました。

react-routerではRouteコンポーネントの render prop をv6からサポートを削除、historyをnavigateへリプレイスしたとのこと。
history.pushに関してはuseNavigateに置き換えれば、問題なさそう。

  • App.ts(新)
App.ts
import React, { useState, useEffect } from 'react';
...
import { useNavigate } from "react-router-dom";

const App: React.FC = (props: any) => {
  const navigate = useNavigate();
  ...
  useEffect(()=>{
    const unSub =auth.onAuthStateChanged((user)=>{
      !user && navigate("login")
    });
    return () => unSub();
  });
...

  return (
  ...
  );
}

export default App;

ということで無事動きました。
(React初心者なので、どこか理解間違っていたら教えてください)

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