[React Bootstrap] Table を表示してみる | 心を無にして始める React

今回は、Table コンポーネントを表示します。

準備
まだ components フォルダがなければ作ります。
src
を右クリックして New Folder
。

components と入力してフォルダを作ります。

今回は、components フォルダに Table のコンポーネントを作って、表示してみます。
公式のドキュメントはここ。
https://react-bootstrap.github.io/components/table/
Table コンポーネントをつくる
component フォルダに Table.js
を作ります。
Table.js
を心を無にして編集してみます。
import React from 'react';
import { Table as BootstrapTable } from 'react-bootstrap';
const Table = React.forwardRef(({
columns,
rows,
...otherProps
}, ref) => {
return (
<BootstrapTable ref={ref} {...otherProps}>
{
columns && (
<thead>
<tr>
{columns.map((column, i) => <th key={i}>{column}</th>)}
</tr>
</thead>
)
}
{
rows && (
<tbody>
{
rows.map(row => (
<tr key={row[0]}>
{row.map((column, i) => <td key={i}>{column}</td>)}
</tr>
))
}
</tbody>
)
}
</BootstrapTable>
)
})
export default Table;
プロジェクトでは、コンポーネントを統一したデザインで利用することが多いです。
そのため、(React Bootstrap のコンポーネントをその場その場でカスタマイズしながら使うよりも、)プロジェクトでコンポーネントにしたものを使うほうが、変更をお手軽に漏れなくできることが多いです。
Table コンポーネントを表示する
それでは、 App.js
を編集して Table コンポーネントを表示します。
import React from 'react';
import './App.css';
import Table from './components/Table';
const COLUMNS = ['No.', 'Name', 'Age'];
const ROWS = [
[1, 'one', 10],
[2, 'two', 8],
[3, 'three', 7],
];
function App() {
return (
<>
<div className="bg-dark" style={{ minHeight: '100vh' }}>
<div className="p-5">
<Table
bordered
hover
striped
variant="dark"
columns={COLUMNS}
rows={ROWS}
/>
</div>
</div>
</>
);
}
export default App;
画面を確認してみます。

はい、できました。