ここでは、Next.js(App Router構成)+ TypeScriptを使い、データ加工のロジックを別ファイルにまとめて利用する方法を解説します。
utils/logic.ts
に分離page.tsx
)でロジック関数やクラスを呼び出して使うproject-root/ ├── app/ │ └── neko-list/ │ └── page.tsx ← 表示ページ ├── utils/ │ └── logic.ts ← ロジックファイル
utils/logic.ts
export type Cat = {
id: number;
name: string;
};
export function formatCatList(cats: Cat[]): Cat[] {
return cats.map((cat) => ({
...cat,
name: cat.name.toUpperCase(),
}));
}
app/neko-list/page.tsx
'use client';
import { formatCatList, Cat } from '@/utils/logic';
const rawCatData: Cat[] = [
{ id: 1, name: 'たま' },
{ id: 2, name: 'みけ' },
{ id: 3, name: 'しろ' },
];
const formattedCatData = formatCatList(rawCatData);
export default function NekoListPage() {
return (
<main className="p-6 bg-gray-50 min-h-screen">
<h1 className="text-2xl font-bold mb-4 text-blue-700">加工済みネコ一覧</h1>
<ul className="space-y-2">
{formattedCatData.map((cat) => (
<li key={cat.id} className="bg-white shadow p-4 rounded border border-gray-200">
ID: {cat.id} / 名前: {cat.name}
</li>
))}
</ul>
</main>
);
}
utils/CatService.ts
export type Cat = {
id: number;
name: string;
};
export class CatService {
private cats: Cat[];
constructor(cats: Cat[]) {
this.cats = cats;
}
toUpperCaseNames(): Cat[] {
return this.cats.map((cat) => ({
...cat,
name: cat.name.toUpperCase(),
}));
}
filterByName(keyword: string): Cat[] {
return this.cats.filter((cat) => cat.name.includes(keyword));
}
}
app/neko-list/page.tsx
(クラス利用)'use client';
import { CatService, Cat } from '@/utils/CatService';
const rawCats: Cat[] = [
{ id: 1, name: 'たま' },
{ id: 2, name: 'みけ' },
{ id: 3, name: 'しろ' },
];
const service = new CatService(rawCats);
const cats = service.toUpperCaseNames();
export default function NekoListPage() {
return (
<main className="p-6 bg-gray-50 min-h-screen">
<h1 className="text-2xl font-bold mb-4 text-blue-700">ネコ一覧(クラス加工)</h1>
<ul className="space-y-2">
{cats.map((cat) => (
<li key={cat.id} className="bg-white shadow p-4 rounded border border-gray-200">
ID: {cat.id} / 名前: {cat.name}
</li>
))}
</ul>
</main>
);
}
ポイント | 内容 |
---|---|
ロジックの分離 | 関数またはクラスにして utils/ に置く |
クラス利用の是非 | Reactコンポーネントには不要。ロジックだけならOK |
設計メリット | 責務の分離、再利用性、保守性アップ |