React Development

Reactテーブルのカラム固定:包括的なガイド

Spread the love

React Tableは表形式のデータを表示するための強力なツールですが、固定列の管理は難しい場合があります。このガイドでは、水平スクロール中に列を固定状態に保つための、バージョンに特化した明確な方法を提供します。

目次

React Table v7以降でreact-table-stickyを使用する

React Table v7では、APIに大きな変更が加えられました。固定列については、react-table-stickyが簡素化されたソリューションを提供します。

1. インストール

npm install react-table-sticky
# または
yarn add react-table-sticky

2. 実装

この例では、「ID」列を左側に固定する方法を示します。


import React from 'react';
import { useTable, useSticky } from 'react-table';
import { FixedColumnsTable } from 'react-table-sticky';

const data = [
  { id: 1, name: 'John Doe', age: 30, city: 'New York' },
  { id: 2, name: 'Jane Doe', age: 25, city: 'London' },
  // ... さらにデータ
];

const columns = [
  { Header: 'ID', accessor: 'id', sticky: 'left' },
  { Header: '名前', accessor: 'name' },
  { Header: '年齢', accessor: 'age' },
  { Header: '都市', accessor: 'city' },
];

function MyTable({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data }, useSticky);

  return (
    <FixedColumnsTable {...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 => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>
    </FixedColumnsTable>
  );
}

export default MyTable;

列定義内のsticky: 'left'プロパティにより、「ID」列が固定されます。右側の列を固定するにはsticky: 'right'を使用します。

React Table v6以前でreact-table-hoc-fixed-columnsを使用する

古いバージョンのReact Tableでは、react-table-hoc-fixed-columnsがHigher-Order Components(HOC)を使用したソリューションを提供します。

1. インストール

npm install react-table-hoc-fixed-columns
# または
yarn add react-table-hoc-fixed-columns

2. 実装

実装は、使用しているReact Tableのバージョンによって異なります。詳細な手順については、ライブラリのドキュメントを参照してください。一般的なアプローチとしては、テーブルコンポーネントをfixedColumns HOCでラップします。簡略化された例(バージョン固有の詳細については、ライブラリのドキュメントを参照):


import React from 'react';
import { useTable } from 'react-table';
import { fixedColumns } from 'react-table-hoc-fixed-columns';

// ... データと列の定義 ...

const MyTable = fixedColumns(({ getTableProps, ...rest }) => (
  <YourOriginalTableComponent {...rest} {...getTableProps()} />
));

// ... コンポーネントの残りの部分

常にreact-table-stickyreact-table-hoc-fixed-columnsの公式ドキュメントを参照して、最も正確で最新の情報を取得してください。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です