zukucode
主にWEB関連の情報を技術メモとして発信しています。

react-router-domでプログラムから画面遷移を行う

react-router-domでプログラムから画面遷移を行う方法を紹介します。

history.psuh(遷移先URL)の形式で実行すると、画面遷移を行えます。

historyreact-router-domuseHistoryというhookから使用できます。

以下の例では、ボタンをクリックしたイベントで画面遷移を行っています。

import { VFC } from 'react';
import { useHistory } from 'react-router-dom';

const Menu: VFC = () => {
  const history = useHistory();

  const move = () => {
    history.push('/about'); // 画面遷移
  };

  return (
    <button type="button" onClick={move}>
      画面遷移
    </button>
  );
};

export default Menu;

関連記事