LoginSignup
28
22

More than 1 year has passed since last update.

Material-UI の DataGrid の中にボタンを配置するサンプル

Last updated at Posted at 2021-06-15

概要

DataGrid にボタンを配置するサンプル。
こういうの。

DataGrid.png

ボタン押下でパラメータを渡せるようにする。

deletebtn.png

一覧のロジック

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';
import Button from '@material-ui/core/Button';
import DeleteButton from './DeleteButton';

// カラム
const columns = [
  // 削除ボタン
  {
    field: 'deleteBtn',
    headerName: '削除',
    sortable: false,
    width: 90,
    disableClickEventBubbling: true,
    renderCell: (params) => <DeleteButton rowId={ params.id } />
  },
  // 詳細ボタン
  {
    field: 'editBtn',
    headerName: '詳細',
    sortable: false,
    width: 90,
    disableClickEventBubbling: true,
    renderCell: (params) => <Button variant="contained" color="primary">詳細</Button>
  },
  { field: 'id', headerName: 'ID', width: 100 },
  { field: 'title', headerName: '本のタイトル', width: 250 },
];

// データ
const rows = [
  { id: 1, title: '君の膵臓をたべたい' },
  { id: 2, title: '容疑者Xの献身' },
  { id: 3, title: 'コンビニ人間' },
  { id: 4, title: '蹴りたい背中' },
  { id: 5, title: '世界の中心で、愛を叫ぶ' },
];

export default function DataGridDemo() {
  return (
    <div style={{ height: 400, width: 600 }}>
      <DataGrid rows={rows} columns={columns} pageSize={5} />
    </div>
  );
}

削除ボタンのロジック

import React, { useState } from 'react';
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from '@material-ui/core';

const DeleteButtonDialog = ({ rowId }) => {
  const [open, setOpen] = useState(false); // 確認ダイアログの表示/非表示

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const deleteRow = (rowId, e) => {
    // (ここで削除処理)
    setOpen(false);
  };

  return (
    <div>
      <Button variant="outlined" color="primary" onClick={handleOpen}>
        削除
      </Button>
      <Dialog
        open={open}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">{'確認'}</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">ID「{rowId}」を本当に削除しますか?</DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} variant="outlined" color="primary" autoFocus>
            やめる
          </Button>
          <Button onClick={(e) => deleteRow(rowId, e)} color="primary">
            削除する
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default DeleteButtonDialog;

CodesandboxのURLを貼っておきます。

28
22
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
28
22