Open6

MUIとこれから仲良くなる方法

sa9sha9sa9sha9

Paginationのロジックを完全にカスタムして外出しする場合、制御/非制御prosのApiRef / paginationModel / setPaginationModel / initialStateはいずれも指定する必要がなく、dataに落ちてくるものをただ表示するだけ、というイメージ。

paginationMode = "server"を指定しなくても動くは動くが、consoleに警告が出るので指定する。

https://mui.com/x/react-data-grid/pagination/

↓Custom Paginationは、MUI のPaginationロジックを乗っかりたい場合のカスタム。完全にカスタムにしたい場合はslotsにすら指定しなくて良い。
https://mui.com/x/react-data-grid/components/#pagination

sa9sha9sa9sha9

Cellにカスタムコンポーネント使う場合に、GridRenderCellParamsに新しいpropを生やす方法

type HogeComponentProps = ComponentProps<typeof HogeComponent>;

function GridHogeCell(
  props: GridRenderCellParams & {
    variant?: HogeComponentProps['variant'];
  },
) {
  if (props.value == null) {
    return null;
  }
  return (
    <HogeComponent
      data={props.value}
      width={props.colDef.computedWidth}
      variant={props.variant}
    />
  );
}

const columns: GridColDef[] = [
  {
    field: 'hoge',
    headerName: 'hoge',
    width: 150,
    renderCell: (params) => <GridHogeCell {...params} variant="primary" />,
  },
];

const rows: [
  {
    id: 0,
    name: 'a',
    hoge: 'hoge'
  }
]

export default function HogeTable() {
  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} />
    </div>
  );
}
sa9sha9sa9sha9

ちなみにvalueGetterでvalueに注入される値を変更できる。

const rows: [
  {
    id: 0,
    name: 'a',
    hoge: 'hoge',
    fuga: 'fuga'
  }
]
const columns: GridColDef[] = [
  {
    field: 'hoge',
    headerName: 'hoge',
    width: 150,
    valueGetter: (value, row) => row.fuga,
    renderCell: (params) => <GridHogeCell {...params}  />, // params.value に通常ならrow.hogeが入るが、row.fugaが注入される
  },
];

sa9sha9sa9sha9

valueFormatterでvalueに注入される値の整形ができる

const rows: [
  {
    id: 0,
    name: 'a',
    hoge: 'hoge',
  }
]
const columns: GridColDef[] = [
  {
    field: 'hoge',
    headerName: 'hoge',
    width: 150,
    valueFormatter: (value) => valueFormatter.format(Number(value)),
    renderCell: (params) => <GridHogeCell {...params}  />, // params.value にformatterで修正されたものが入る
  },
];