Reputation: 181
I'm using a Material ui component called DataTable, and I don't know how to detect a click in any cell in a specific column
This is my table and I want to handle a click in any cell in the Action column:
below my component code:
import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { PropTypes } from 'prop-types';
export default function DataTable({ rows, columns }) {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
/>
</div>
);
}
DataTable.propTypes = {
rows: PropTypes.arrayOf(
PropTypes.shape({
conteudo: PropTypes.string,
disciplina: PropTypes.string,
curso: PropTypes.string,
data: PropTypes.string,
})
).isRequired,
// eslint-disable-next-line react/forbid-prop-types
columns: PropTypes.array.isRequired,
};
Upvotes: 8
Views: 17818
Reputation: 6895
You can handle any click event on any column by passing onCellClick
prop to your DataGrid
like this:
import { useState } from "react";
import { DataGrid } from "@mui/x-data-grid";
export default function DataTable({ rows, columns }) {
const [finalClickInfo, setFinalClickInfo] = useState(null);
const handleOnCellClick = (params) => {
setFinalClickInfo(params);
};
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
onCellClick={handleOnCellClick}
/>
{finalClickInfo &&
`Final clicked id = ${finalClickInfo.id},
Final clicked field = ${finalClickInfo.field},
Final clicked value = ${finalClickInfo.value}`}
</div>
);
}
You can access any property like id
, field
, value
etc. from the value that is returned from onCellClick
function. You can take a look at this stackblitz for a live working example of this usage.
Upvotes: 15