サンプルイメージ
Reactでページ遷移する方法についてポイント
React(Vite や CRA など)はReact Routerを使ってルーティングを定義しないとページ遷移しません。
ReactとNext.jsのページ遷移は全く異なるので、Reactアプリなのか、Next.jsアプリなのかをはっきり意識しておきましょう。
こんかいは、Reactアプリを使うので、ページ遷移に必要な設定方法を下記に記載していきます。
1. React Router をインストール
下記のコマンドでReact Routerモジュールをインストールします。
npm install react-router-dom
2. ルーティングを作成
つぎに、src/App.tsxにルーティング設定を追記します。
2-1.ルーティングに必要なモジュールをインポート
ルーティングに必要なモジュールをインポートします。
import { BrowserRouter, Routes, Route } from 'react-router-dom';
2-2.遷移先のコンポーネントを読み込む
import { 遷移先のコンポーネント } from '遷移先のコンポーネントパス';
今回は、InputProductForm コンポーネントを遷移先のページに設定するので下記のように記載します。
import { InputProductForm } from './pages/products/input-form/page';
2-3.Navbar のリンクを<Link>に変更(任意:NavBarからページ遷移する場合)
React では<a href="...">を使うとSPAの挙動が壊れるので
必ずReact Routerの<Link>を使います。
【例】
<Link to="/" className="hover:text-gray-200">ホーム</Link>
src/components/navbar/page.tsxの全体コードは下記です。
import { Link } from "react-router-dom";
const Navbar: React.FC = () => {
return (
<nav className="bg-blue-600 text-white px-6 py-4 flex justify-between items-center">
<div className="text-xl font-bold">MyApp</div>
<div className="space-x-4 flex items-center">
<Link to="/" className="hover:text-gray-200">ホーム</Link>
<Link to="/products/input-form" className="hover:text-gray-200">サービス</Link>
</div>
</nav>
);
};
export default Navbar;
ルーティング設定後のApp.tsxのコード
App.tsxの全体コードは下記です。
import { BrowserRouter, Routes, Route } from 'react-router-dom'; //追加
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Navbar from './components/navbar/page';
import { InputProductForm } from './pages/products/input-form/page';
const App: React.FC = () => {
const [message, setMessage] = useState<string>('');
{
/* 開発用.envから設定情報を読み込む*/
}
const topUrl = import.meta.env.VITE_TOP_URL;
useEffect(() => {
{
/* 開発用.envから設定情報「REACT_APP_TOP_URL」がnullの場合*/
}
if (!topUrl) {
alert('URL情報がありません。');
return;
}
axios
.get(topUrl)
.then((response) => {
setMessage(response.data);
console.log(`Nest.jsサーバから取得したデータは、${response.data}です。`);
})
.catch((error) => {
console.error('There was an error!', error);
});
}, []);
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/products/input-form" element={<InputProductForm />} />
</Routes>
</BrowserRouter>
);
};
export default App;
これで、NavBarの「サービス」リンクをクリックすると、ページ遷移が設定できました。
別ページへ遷移するときの設定
ページ遷移先から別ページへ戻るときは等したらよいかというと、React-RouterのuseNavigateモジュールを使います。
1.クラスファイルの冒頭で``useNavigateモジュールをインポートします。 2.つぎに、関数内部でuseNavigate`モジュールを設定します。
3.さいごに、ボタンを押下した場合の処理の中に遷移先のパスを記載します。
import { useNavigate } from "react-router-dom";
export const InputProductForm = () => {
{/* useNavigateモジュールを定義 */}
const navigate = useNavigate();
{/* トップページ戻るボタンクリック時の処理 */}
const clickBakToTopPage = ()=>{
navigate('/');
}
//(略)
全体のサンプル⇩
import { useNavigate } from "react-router-dom";//ページ遷移用モジュール
export const InputProductForm = () => {
{/* useNavigateモジュールを定義 */}
const navigate = useNavigate();
{/* トップページ戻るボタンクリック時の処理 */}
const clickBakToTopPage = ()=>{
navigate('/');
}
return (
<div className="w-full max-w-xs">
<form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="productname">
商品名
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 mb-4 text-gray-700 focus:outline-none focus:shadow-outline"
placeholder="商品名"
/>
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="productname">
価格
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 mb-4 text-gray-700 focus:outline-none focus:shadow-outline"
placeholder="価格"
/>
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="productname">
説明
</label>
<textarea
className="shadow appearance-none border rounded w-full py-2 px-3 mb-4 text-gray-700 focus:outline-none focus:shadow-outline"
placeholder="説明"
/>
<div className="flex items-center justify-between">
<button
type="button"
className="bg-blue-500 hover:bg-blue-700 font-bold text-white rounded px-4 py-2 mr-2 cursor-pointer"
>
確認画面へ進む
</button>
<button
type="button"
className="bg-green-500 hover:bg-green-700 font-bold text-white rounded px-4 py-2 mr-2 cursor-pointer"
onClick={clickBakToTopPage}
>
ホームへ戻る
</button>
<button
type="button"
className="bg-gray-500 hover:bg-gray-700 font-bold text-white rounded px-4 py-2 mr-4 cursor-pointer"
>
クリア
</button>
</div>
</div>
</form>
</div>
);
};
サイト
【React】図でわかる!初心者のためのReact Routerによる画面遷移の手順
TailWindCSS Forms


