3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

react-table の使い方

Last updated at Posted at 2022-08-01

こちらのページを参考にしました。
Reactの機能で簡単にテーブル(表組み)を作る方法【react-table使います】

次のようなテーブルを作成します。
image.png

プロジェクトの作成

create-react-app ex04
cd ex04
yarn add react-table
yarn start

次のプログラムを修正します。
src/App.js
src/App.css

次は加えます。
src/tableData.jsx

src/App.js
// eslint-disable-next-line

import React from "react";
import { useTable } from "react-table";
import { columns, data } from "./tableData";
import "./App.css";

export default function App() {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
                            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>
                              {column.render("Header")}
                            </th>
            ))}
          </tr>
        ))}
      </thead>

      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return (
                  <td {...cell.getCellProps()}>
         {cell.render("Cell")}
                 </td>
                )
              })}
            </tr>
                            );
        })}
      </tbody>
    </table>
  );
}
src/App.css
/* -------------------------------------------------------------- */
/*

        App.css

                                                Aug/02/2022

*/
/* -------------------------------------------------------------- */
table,td,th {
        width: 80%;
        table-layout: fixed;
        border:1.5px #7e7e7e solid;
}

th { background: #c6c6c6; }


/* -------------------------------------------------------------- */
src/tableData.jsx
export const columns = [
  { Header: "商品", accessor: "product" },
  { Header: "値段", accessor: "price" },
  { Header: "在庫", accessor: "stock" }
];

export const data = [
  { product: "りんご", price: "120円", stock: "130" },
  { product: "バナナ", price: "100円", stock: "200" },
  { product: "メロン", price: "3400円", stock: "2" },
  { product: "ぶどう", price: "1200円", stock: "6" }
];

次の環境で確認しました。

$ node --version
v18.7.0
$ yarn --version
1.22.19
3
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?