はじめに
これの続きです。
STEP
・要件整理(画面デザイン作成)
・フロンドエンド開発
・静的画面
・表示切り替え(useState)
・画面遷移(useRouter) ←いまここ
・APIモック作成
・バックエンド開発
今回のやることとゴール
このSTEPではひとつ前の工程作成したログイン画面から、メイン画面への遷移処理を追加します。
目次
1. ボタン押下時の処理をCopilotに伝える
開発開始
このコードを修正していきます。
src\app\login\page.tsx
'use client'
import { useState, Dispatch, SetStateAction } from 'react'
interface LoginFormProps {
setIsLoginView: Dispatch<SetStateAction<boolean>>
}
export default function LoginForm({ setIsLoginView }: LoginFormProps) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<>
<form className="space-y-6">
~省略~
<button
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
>
ログイン
</button>
</form>
~省略~
</>
)
}
作業ファイルを設定して、以下の呪文を唱えます。
ログインボタンをクリックすると/dashboardに遷移する。
isLoading中の場合、ボタンには「ログイン中...」を表示し、ボタンは非活性とする。
修正後src\app\login\page.tsx
'use client'
import { useState, Dispatch, SetStateAction } from 'react'
import { useRouter } from 'next/navigation'
interface LoginFormProps {
setIsLoginView: Dispatch<SetStateAction<boolean>>
}
export default function LoginForm({ setIsLoginView }: LoginFormProps) {
const router = useRouter()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
try {
// TODO: 実際のログイン処理をここに実装
await new Promise(resolve => setTimeout(resolve, 1000)) // ログイン処理のシミュレーション
router.push('/dashboard')
} catch (error) {
console.error('Login failed:', error)
} finally {
setIsLoading(false)
}
}
return (
<>
<form className="space-y-6" onSubmit={handleSubmit}>
~省略~
<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
>
{isLoading ? 'ログイン中...' : 'ログイン'}
</button>
</form>
~省略~
</>
)
}
完成!!
動かしてみよう
クリック後のボタン
画面遷移
まとめ
画面遷移は簡単でしたね。