TODOを空白で登録しようとした際のダイアログをカスタム化+UI調整

This commit is contained in:
2025-07-12 17:33:40 +09:00
parent cd0e6cca9f
commit 62e2942cb9

View File

@@ -15,20 +15,21 @@ export default function Home() { // Reactコンポーネント。Next.jsのデ
const [inputValue, setInputValue] = useState<string>(''); // 入力欄の中身。初期値は空文字。 const [inputValue, setInputValue] = useState<string>(''); // 入力欄の中身。初期値は空文字。
const [showConfirm, setShowConfirm] = useState(false); // 削除確認ダイアログを表示するかどうか。 const [showConfirm, setShowConfirm] = useState(false); // 削除確認ダイアログを表示するかどうか。
const [targetId, setTargetId] = useState<number | null>(null); // 確認ダイアログで削除対象のTodoのIDを一時保持。 const [targetId, setTargetId] = useState<number | null>(null); // 確認ダイアログで削除対象のTodoのIDを一時保持。
const [showInputAlert, setShowInputAlert] = useState(false); // 空欄入力時の警告ダイアログ
// 新しいTODOを追加する関数 // 新しいTODOを追加する関数
const addTodo = () => { const addTodo = () => {
if (inputValue.trim() === '') { // 入力が空欄だったら処理を中止。trim()で空白も除去。 if (inputValue.trim() === '') { // 入力が空欄だったら処理を中止。trim()で空白も除去。
alert('TODOを入力してください'); setShowInputAlert(true); // カスタムダイアログ表示
return; return;
} }
const newTodo: Todo = { const newTodo: Todo = {
id: Date.now(), // 現在時刻をミリ秒単位でIDとして使用。実運用ではuuid推奨。 id: Date.now(),
text: inputValue, // 入力欄の内容を設定。 text: inputValue,
completed: false // 初期状態では未完了。 completed: false
}; };
setTodos([...todos, newTodo]); // 既存の配列に新しいTodoを追加。イミュータブルに保つため新配列を生成。 setTodos([...todos, newTodo]);
setInputValue(''); // 入力欄を初期化。 setInputValue('');
}; };
// フォームが送信されたときの処理 // フォームが送信されたときの処理
@@ -69,6 +70,12 @@ export default function Home() { // Reactコンポーネント。Next.jsのデ
setTargetId(null); setTargetId(null);
}; };
// 空欄入力時ダイアログを閉じる関数
const closeInputAlert = () => {
setShowInputAlert(false);
};
// JSX: 実際に表示されるUI定義 // JSX: 実際に表示されるUI定義
return ( return (
<main className="min-h-screen p-8 bg-gray-50"> {/* 全体の背景や余白 */} <main className="min-h-screen p-8 bg-gray-50"> {/* 全体の背景や余白 */}
@@ -125,6 +132,22 @@ export default function Home() { // Reactコンポーネント。Next.jsのデ
</div> </div>
</div> </div>
)} )}
{/* 空欄入力時のカスタムダイアログ */}
{showInputAlert && (
<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 flex flex-col items-center">
<p className="mb-4">TODOを入力してください</p>
<button
onClick={closeInputAlert}
className="w-full px-4 py-2 bg-blue-500 text-white rounded text-center"
style={{ maxWidth: "240px" }}
>
</button>
</div>
</div>
)}
</div> </div>
</main> </main>
); );