LoginSignup
2
0

More than 3 years have passed since last update.

Reactのmaterial-tableでDetail Panelを閉じる

Last updated at Posted at 2021-03-16

目的

Reactのmaterial-tableには行の詳細をパネル表示する DetailPanelが用意されていますが、Detail Panelの開閉処理は自分で実装する必要があります。このページは開いているDetail Panelを閉じる処理の実装の覚書です。

仕様

  • CloseボタンをdetailPanelの中に設置します
  • Closeボタンを押したら、開いているDetailPanelを閉じます

環境

  • React 17.0
  • material-table 1.69.2
  • @material-ui/core 4.11.3
  • @material-ui/icons 4.11.2

実装

1. tableRefの指定

material-tableではテーブル操作のために props tableRef でrefを渡せるので、refを作成してpropsで指定します

const tableRef = React.createRef();
(略)
<MaterialTable tableRef={tableRef} (そのほかのprops)

2. Detail Panelsを作成し、Closeボタンを配置する

Detail Panel | material-table公式 を参考に実装します

3. ボタンにイベントリスナを実装する

<Button (そのほかのprops) onClick={() => handleClose(rowData)}>Close</Button>

4. Detail Panelを閉じる関数を作成する

GitHubのコメントを参考にしました
https://github.com/mbrn/material-table/issues/2437#issuecomment-691086290

  const handleClose = (rowData) => {
    tableRef.current.onToggleDetailPanel(
      [rowData.tableData.id],
      tableRef.current.props.detailPanel
    );
  };

onToggleDetailPanel 関数はDetail Panelの開閉を切り替えるので、これをrefを使って呼び出すと、開いているDetail Panelを閉じることができます。

サンプル

CodeSandboxに置いてあります
https://codesandbox.io/s/react-material-ui-detail-panel-close-demo-zj3kx?file=/src/App.js

参考

2
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
2
0