🖥️
Next.js入門5 Todoアプリ(タスク一覧)
記事一覧
- Next.js × Docker 最速環境構築
- Next.js入門1 ページ追加
- Next.js入門2 コンポーネント
- Next.js入門3 無記名関数 & イベントハンドラー
- Next.js入門4 Hooks
- Next.js入門5 Todoアプリ(タスク一覧)
- Next.js入門6 Todoアプリ(タスク追加)
- Next.js入門7 Todoアプリ(タスク詳細)
- Next.js入門8 Todoアプリ(タスク編集, 削除)
タスク一覧
http://localhost:3000/task
でアクセスできるタスク一覧ページを作る
型を定義
-
task.ts
を作成
.
├── next-app
│ └── types
│ └── task.ts # ここに作成
├── docker-compose.yml
└── Dockerfile
-
task.ts
を記述
// exportをつけることで他ファイルから使用できるようにする
// type 型の名前 = {
export type Task = {
title: string;
content: string;
};
コンポーネントを作成
-
table.tsx
を作成
.
├── next-app
│ └── components
│ └── table.tsx # ここに作成
├── docker-compose.yml
└── Dockerfile
-
table.tsx
を記述
// Task型をインポート
import { Task } from "@/types/task";
// 引数の型を定義
type Props = {
// タスクを配列形式で受け取る
tasks: Task[];
};
// Tableコンポーネントを定義
export function Table({ tasks }: Props) {
return (
<table className="w-full [&_td]:p-2 [&_td]:border">
<thead>
<tr>
<td>タイトル</td>
<td className="w-2/3">内容</td>
</tr>
</thead>
<tbody>
{/* 渡されたtasksを回してテーブルを列を作成する */}
{tasks.map((task, index) => (
<tr key={index}>
<td>{task.title}</td>
<td>{task.content}</td>
</tr>
))}
</tbody>
</table>
);
}
ページを作成
-
task/page.tsx
を作成
.
├── next-app
│ └── app
│ └── task
│ └── page.tsx # ここに作成
├── docker-compose.yml
└── Dockerfile
-
task/page.tsx
を記述
"use client";
import { useState } from "react";
// Tableコンポーネントのインポート
import { Table } from "@/components/table";
// Task型のインポート
import { Task } from "@/types/task";
function Page() {
// useState<型>で型を定義できる
const [tasks, setTasks] = useState<Task[]>([
{ title: "タスク1", content: "タスク1の内容" },
{ title: "タスク2", content: "タスク2の内容" },
{ title: "タスク3", content: "タスク3の内容" },
]);
return (
<div className="flex flex-col gap-8 items-center p-16">
<h1 className="text-4xl font-bold">タスク一覧</h1>
{/* Tableコンポーネントにtasksを渡す */}
<Table tasks={tasks}></Table>
</div>
);
}
export default Page;
Discussion