forked from semi-23e/nextjs-todo-tutorial
コード全体に質疑応答補助用のコメントアウトを追加
This commit is contained in:
111
src/app/page.tsx
111
src/app/page.tsx
@@ -1,70 +1,86 @@
|
||||
'use client'; // ← 重要!状態管理を使う時は必須
|
||||
'use client'; // ← これはNext.jsのApp Routerで、クライアントコンポーネントとして実行させる指示。useStateなどクライアント専用フックを使うために必須。
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState } from 'react'; // Reactの"状態管理用"のフック。状態が変化したら再レンダリングが起きる。
|
||||
|
||||
// TypeScriptの型定義
|
||||
// Todo型の定義。オブジェクトが必ずid, text, completedというプロパティを持つことを保証。
|
||||
type Todo = {
|
||||
id: number; // 一意の識別子
|
||||
text: string; // TODOの内容
|
||||
completed: boolean; // 完了状態
|
||||
id: number; // ユニークな識別子。今回はDate.now()で一意性をある程度確保。
|
||||
text: string; // TODOの内容。ユーザーが入力する文字列。
|
||||
completed: boolean; // 完了したかどうかのフラグ。チェックボックスに対応。
|
||||
};
|
||||
|
||||
export default function Home() {
|
||||
// useState フックの使い方
|
||||
const [todos, setTodos] = useState<Todo[]>([]);
|
||||
const [inputValue, setInputValue] = useState<string>('');
|
||||
export default function Home() { // Reactコンポーネント。Next.jsのデフォルトエクスポートとしてトップページに描画される。
|
||||
// 状態変数定義。todosはTodoの配列、inputValueは入力中のテキスト。
|
||||
const [todos, setTodos] = useState<Todo[]>([]); // Todoリスト本体。初期値は空配列。
|
||||
const [inputValue, setInputValue] = useState<string>(''); // 入力欄の中身。初期値は空文字。
|
||||
const [showConfirm, setShowConfirm] = useState(false); // 削除確認ダイアログを表示するかどうか。
|
||||
const [targetId, setTargetId] = useState<number | null>(null); // 確認ダイアログで削除対象のTodoのIDを一時保持。
|
||||
|
||||
// 新しいTODOを追加する関数
|
||||
const addTodo = () => {
|
||||
// 空の入力をチェック(バリデーション)
|
||||
if (inputValue.trim() === '') {
|
||||
if (inputValue.trim() === '') { // 入力が空欄だったら処理を中止。trim()で空白も除去。
|
||||
alert('TODOを入力してください');
|
||||
return;
|
||||
}
|
||||
const newTodo: Todo = {
|
||||
id: Date.now(), // 簡易的なID生成(本番ではuuidを推奨)
|
||||
text: inputValue,
|
||||
completed: false
|
||||
id: Date.now(), // 現在時刻をミリ秒単位でIDとして使用。実運用ではuuid推奨。
|
||||
text: inputValue, // 入力欄の内容を設定。
|
||||
completed: false // 初期状態では未完了。
|
||||
};
|
||||
setTodos([...todos, newTodo]);
|
||||
setInputValue('');
|
||||
setTodos([...todos, newTodo]); // 既存の配列に新しいTodoを追加。イミュータブルに保つため新配列を生成。
|
||||
setInputValue(''); // 入力欄を初期化。
|
||||
};
|
||||
|
||||
// フォームが送信されたときの処理
|
||||
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault(); // ページのリロードを防ぐ
|
||||
addTodo();
|
||||
e.preventDefault(); // ページ全体のリロードを防ぐ。SPA的挙動にする。
|
||||
addTodo(); // addTodo関数を実行。
|
||||
};
|
||||
|
||||
// Todoの完了状態をトグル(反転)する関数
|
||||
const toggleTodo = (id: number) => {
|
||||
// mapを使って新しい配列を作成(イミュータビリティ)
|
||||
const updatedTodos = todos.map(todo => {
|
||||
if (todo.id === id) {
|
||||
// 該当するTODOを見つけたら、completedを反転
|
||||
return { ...todo, completed: !todo.completed };
|
||||
return { ...todo, completed: !todo.completed }; // 対象のcompletedだけ反転。
|
||||
}
|
||||
return todo; // それ以外はそのまま
|
||||
return todo; // それ以外はそのまま。
|
||||
});
|
||||
|
||||
setTodos(updatedTodos);
|
||||
setTodos(updatedTodos); // 新しい配列をset。Reactはこれを検知して再描画する。
|
||||
};
|
||||
|
||||
const deleteTodo = (id: number) => {
|
||||
// 確認ダイアログを表示(オプション)
|
||||
if (confirm('本当に削除しますか?')) {
|
||||
// filterを使って該当ID以外の要素で新しい配列を作成
|
||||
const filteredTodos = todos.filter(todo => todo.id !== id);
|
||||
setTodos(filteredTodos);
|
||||
// 削除ボタンが押されたときの仮処理。確認ダイアログを表示。
|
||||
const handleDeleteClick = (id: number) => {
|
||||
setShowConfirm(true); // ダイアログ表示
|
||||
setTargetId(id); // 対象ID記憶
|
||||
};
|
||||
|
||||
// ダイアログで「はい」が押されたときの本削除処理
|
||||
const confirmDelete = () => {
|
||||
if (targetId !== null) { // nullチェックを忘れずに
|
||||
setTodos(todos.filter(todo => todo.id !== targetId)); // 該当ID以外を残す
|
||||
setShowConfirm(false); // ダイアログを閉じる
|
||||
setTargetId(null); // 状態を初期化
|
||||
}
|
||||
};
|
||||
|
||||
// ダイアログで「いいえ」が押されたときの処理
|
||||
const cancelDelete = () => {
|
||||
setShowConfirm(false);
|
||||
setTargetId(null);
|
||||
};
|
||||
|
||||
// JSX: 実際に表示されるUI定義
|
||||
return (
|
||||
<main className="min-h-screen p-8 bg-gray-50">
|
||||
<div className="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">
|
||||
<main className="min-h-screen p-8 bg-gray-50"> {/* 全体の背景や余白 */}
|
||||
<div className="max-w-md mx-auto bg-white rounded-lg shadow-md p-6"> {/* カード風の白背景 */}
|
||||
<h1 className="text-2xl font-bold text-gray-800 mb-6">TODOアプリ</h1>
|
||||
{/* JSX部分 */}
|
||||
|
||||
{/* 入力フォーム */}
|
||||
<form onSubmit={handleSubmit} className="mb-4">
|
||||
<input
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
value={inputValue} // stateと連動
|
||||
onChange={(e) => setInputValue(e.target.value)} // 入力をリアルタイムに反映
|
||||
placeholder="TODOを入力してEnterキー"
|
||||
className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
@@ -75,22 +91,22 @@ export default function Home() {
|
||||
追加
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* TODOリスト */}
|
||||
<div className="space-y-2">
|
||||
{todos.map((todo) => (
|
||||
<div key={todo.id} className="flex items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={todo.completed}
|
||||
onChange={() => toggleTodo(todo.id)}
|
||||
checked={todo.completed} // 完了状態を反映
|
||||
onChange={() => toggleTodo(todo.id)} // トグル動作
|
||||
className="mr-3 h-5 w-5 cursor-pointer"
|
||||
/>
|
||||
<span
|
||||
className={`flex-1 ${todo.completed ? 'line-through text-gray-500' : 'text-gray-800'}`}
|
||||
>
|
||||
<span className={`flex-1 ${todo.completed ? 'line-through text-gray-500' : 'text-gray-800'}`}>
|
||||
{todo.text}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => deleteTodo(todo.id)}
|
||||
onClick={() => handleDeleteClick(todo.id)}
|
||||
className="text-red-500 hover:text-red-700 ml-2 px-2 py-1 rounded transition-colors"
|
||||
>
|
||||
削除
|
||||
@@ -98,6 +114,17 @@ export default function Home() {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 確認ダイアログ */}
|
||||
{showConfirm && (
|
||||
<div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
|
||||
<div className="bg-white p-6 rounded shadow">
|
||||
<p className="mb-4">本当に削除しますか?</p>
|
||||
<button onClick={confirmDelete} className="mr-2 px-4 py-2 bg-red-500 text-white rounded">はい</button>
|
||||
<button onClick={cancelDelete} className="px-4 py-2 bg-gray-300 rounded">いいえ</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user