プロジェクトの作成
mkdir proj01
cd proj01
npm init -y
npm install --save react react-dom next
mkdir pages
package.json の改造
package.json
{
"name": "proj01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^12.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
コードの作成
フォルダー構造
$ tree pages/
pages/
├── Header.js
├── Layout.js
├── index.js
└── pets.js
pages/index.js
import Layout from "./Layout"
export default function Index() {
return (
<Layout>
<div>
<h1>Hello everyone!</h1>
<p>May/23/2022 PM 15:50</p>
</div>
</Layout>
)
}
pages/pets.js
import Layout from "./Layout";
import fetch from "isomorphic-unfetch";
export default function Pets(props) {
return (
<Layout>
<div>
<h1>Pets!</h1>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>category</th>
</tr>
</thead>
<tbody>
{props.pets.map(pet => (
<tr id={pet.id}>
<td>{pet.id}</td>
<td>{pet.name}</td>
<td>{pet.category}</td>
</tr>
))}
</tbody>
</table>
<p>May/23/2022 PM 15:50</p>
</div>
</Layout>
);
}
Pets.getInitialProps = async function() {
const res = await fetch(
`https://pet-library.moonhighway.com/api/pets`
);
const data = await res.json();
return {
pets: data
};
};
pages/Layout.js
import Header from "./Header"
export default function Layout(props) {
return (
<div>
<Header />
{props.children}
</div>
)
}
pages/Header.js
import Link from "next/link"
export default function Header(){
return (
<div>
<Link href="/">
<a>Home</a>
</Link>
<Link href="/pets">
<a>Pets</a>
</Link>
</div>
)
}
サーバーの起動
npm run dev
ブラウザーで
http://localhost:3000
にアクセス