3
0

More than 1 year has passed since last update.

Next.js: テーブルの表示

Last updated at Posted at 2022-05-23

プロジェクトの作成

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>
		&nbsp;
		&nbsp;
		&nbsp;
		<Link href="/pets">
		<a>Pets</a>
		</Link>
	</div>
	)
}

サーバーの起動

npm run dev

ブラウザーで
http://localhost:3000
にアクセス
image.png

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0