Manush
Manush

Reputation: 1942

Create dynamic action column in React Material UI Table

I have a DataTable component that contains Material React Table. I pass the column and row data as props to the DataTable component. I now wanted to add an action column having option like edit and delete. I got stuck here. I provide my code below, kindly provide solution

<DataTable
                    columns={COLUMN_DATA}
                    columnsUniqueKey='colId'
                    rowsUniqueKey='rowId'
                    rows={ROW_DATA}
                    pagination={false}
 /> 

import React from 'react';
import moment from "moment";
import StatusLabel from "../../../../components/StatusLabel/StatusLabel";
import { Button } from '@material-ui/core';


export const COLUMN_DATA = [
    {
        id: "key",
        label: "Key",
    },
    {
        id: "value",
        label: "Value",
    },
    {
        id: "createdAt",
        label: "Create At",
    },
    {
        id: "updatedAt",
        label: "Updated At",
    },
    {
        id: "actions",
        label: "Actions",
    }
]


const createData = (key, value, createdAt, updatedAt, actions) => {
    return {
        key,
        value,
        createdAt,
        updatedAt,
        actions
    };
}


export const ROW_DATA = [
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(1, 'day').format('LLL'),
        moment().subtract(1, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(2, 'day').format('LLL'),
        moment().subtract(2, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(3, 'day').format('LLL'),
        moment().subtract(3, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(4, 'day').format('LLL'),
        moment().subtract(4, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(5, 'day').format('LLL'),
        moment().subtract(5, 'day').format('LLL'),
        <>
            <Button variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
];

And my DataTable component file

import React from 'react';
// styles
import useStyles from "./styles";
import {
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow,
    TableSortLabel
} from '@material-ui/core';
import { DATA_TABLE_ROWS_PER_PAGE_OPTIONS } from './constants';



const DataTable = ({ columns, rows, enableActions, pagination, ...props }) => {


  const classes = useStyles();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = event => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };


  //Row Click Event
  const onRowClicked = row => (event) => {
    // props.rowClicked(row)
  }



  return (
      <>
        <TableContainer className={classes.container}>
            <Table stickyHeader>
            <TableHead>
                <TableRow>
                {columns.map(({sortable, ...column}) => (
                    <TableCell
                    key={column[props.columnsUniqueKey]}
                    align={column.align}>
                        { sortable ? <TableSortLabel>
                                        {column.label}
                                     </TableSortLabel> : column.label }
                    </TableCell>
                ))}

                {/* { enableActions && <TableCell>
                    Actions
                </TableCell> } */}


                </TableRow>
            </TableHead>
            <TableBody>
                { ( pagination ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows).map(row => {
                return (
                    <TableRow onClick={onRowClicked(row)} hover role="checkbox" tabIndex={-1} key={row[props.rowsUniqueKey]}>
                        { columns.map( column => {
                            const value = row[column.id];
                            return (
                                <>
                                    <TableCell key={column[props.columnsUniqueKey]} align={column.align}>
                                        { column.format && typeof value === 'number' ? column.format(value) : value }
                                    </TableCell>
                                </>
                            );
                        }) }
                        {/* { enableActions && <TableCell> Actions </TableCell> } */}
                    </TableRow>
                );
                })}
            </TableBody>
            </Table>
        </TableContainer>
        {pagination && <TablePagination
            rowsPerPageOptions={DATA_TABLE_ROWS_PER_PAGE_OPTIONS}
            component="div"
            count={rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onChangePage={handleChangePage}
            onChangeRowsPerPage={handleChangeRowsPerPage}
        />}
      </>
  );
}

export default DataTable;

How can I add handlers to edit button and pass the column data so that I can handle the event the parent component

Upvotes: 4

Views: 14048

Answers (1)

Nidhi Dadiya
Nidhi Dadiya

Reputation: 839

You don't need to add an edit button every time you create data. also you should call create data once while fetching data. no need to call it every time for Row data.

Here's the codesandbox link with working demo. Try more demo for table and material ui in react here.

Upvotes: 2

Related Questions