material-react-table onRowSelectionChange

# react 16.x -> 19.x 버전업을 하면서 MaterialUI(MUI)도 4x.-> 7.x 로 버전업이 필요했다.
# MUI 이 버전업 됨에 따라 
# material-table(https://github.com/mbrn/material-table)v1 이 MUI v4만 지원하기 때문에 
# material-react-table(https://github.com/KevinVandy/material-react-table)도 v3.x 로 버전업하게 되었다.

# row 별로 체크하고 삭제하는 기능이
# v1 에선 action 이라는 속성이 있어 다음과 같이 구현하면 됐다.
const actions = 
  actionState === "edit"
    ? [
        {
          icon: (props) => <DeleteIcon color="error" />,
          onClick: (event, items) => {
            this.deleteItems(items);
          },
        },
      ]
    : [];
... 생략 ...
return (
<MaterialTable                
  actions={actions}           
/>      
... 생략 ...                   
# v3 에선 action 이라는 속성은 없고 다음과 같이 선택한 row 를 파악해야 한다.
class ManagementPanel extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      items: List(), // immutable 패키지 list 사용시, 아니면 items:{} 로 사용
      actionState: "init",
      rowSelection: {}, // 선택된 row 상태
    };
... 생략 ...
  deleteItems(items) {
    ...  삭제 로직 ...
    // 선택 상태 초기화
    this.setState({
      rowSelection: {},
    });
  }
... 생략 ...
  handleRowSelectionChange = (updater) => {
    // console.log("updater:", updater);
    // updater는 함수 또는 객체일 수 있음
    const rowSelection =
      typeof updater === "function"
        ? updater(this.state.rowSelection)
        : updater;
    this.setState({ rowSelection });
    // console.log("rowSelection:", rowSelection);
  };
  handleGetSelectedRows = () => {
    // 선택된 행의 원본 데이터 추출
    const selectedData = Object.keys(this.state.rowSelection)
      .filter((key) => this.state.rowSelection[key])
      .map((key) => {
        // console.log("this.state.items.toArray():", this.state.items.toArray());
        // console.log("key", key);
        const row = this.state.items.find((row) => {
          // console.log("row.id", row.id);
          // console.log("key", parseInt(key, 10));
          if (row.id == parseInt(key, 10)) {
            console.log("row.id", row.id);
          }
          return row.id == parseInt(key, 10);
        });
        return row ? row : null;
      })
      .filter((row) => row !== null);
    // console.log("선택된 데이터:", selectedData);
    this.deleteItems(selectedData);
  };
... 생략 ...
return (
  <Paper>
    <Toolbar>
      <React.Fragment>
        <FormControl>
          <Button
            color="error"
            onClick={this.handleGetSelectedRows}
            disabled={actionState !== "edit"}
            style={{ marginLeft: "10px" }}
          >
            <DeleteIcon></DeleteIcon>
          </Button>
        </FormControl>
      </React.Fragment>
... 생략 ...
<MaterialReactTable
  enableRowSelection={actionState === "edit"}
  enableSorting={false}
  onRowSelectionChange={this.handleRowSelectionChange}
  state={{ rowSelection: this.state.rowSelection }}
... 생략 ...

# 그외 v3 에서 변경된점
# - column 생성시 header(컬럼 제목), accessorKey(컬럼에 값을 매칭할때 필요) 필드가 설정되어야 한다.
# - 각 row 아이템은 id 필드값으 유니크하게 설정되어야 한다.

comments:

댓글 쓰기