6
2

More than 3 years have passed since last update.

reactのmaterial-tableで一部カラムのみを編集可能にする

Posted at

Material-table

https://material-table.com/#/
Material-uiに則ったテーブルレイアウトを簡単に作成できるライブラリ。一部のカラムを編集できるデータの一覧表を実装したくて採用。

編集可能にしてみる

https://material-table.com/#/docs/features/editable
には「Row Editing」(行単位の一括編集)と「Cell Editing」(セル単位での編集)について記載があった。「Row Editing」の方は行の全カラムが編集可能になってしまい、編集可能にする必要のないカラムがあることから、「Cell Editing」の方かなと思い実装してみる。

const columnList = [
  { title: "ID", field: "id" },
  { title: "name", field: "name" },
  { title: "description", field: "description" },
];

const dataList = [
  { id: 1, name: "aaa", description: "xxxxxxxxxx" },
  { id: 2, name: "bbb", description: "yyyyyyyyyy" },
  { id: 3, name: "ccc", description: "zzzzzzzzzz" },
];

<MaterialTable
  columns={columnList}
  data={dataList}
  cellEditable={{
    onCellEditApproved: (newValue, oldValue, rowData, columnDef) => {
      return new Promise(() => {
        // do something
      });
    },
  }}
></MaterialTable>

結果、セル単位での編集にはなったものの、全セルが編集可能になってしまった。(ID列は編集させたくない)

image.png

一部のセルだけ編集可能にするには…

const columnList = [
  { title: "ID", field: "id", editable: "never" },
  { title: "name", field: "name" },
  { title: "description", field: "description" },
];

editable: "never"

をカラムの定義につけてあげると、そのカラムは編集不可になった。(ID列をクリックしても編集欄が表示されないけど、それ以外の列は編集可能)

image.png

参考になれば幸いです。

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