React - how to handle a cell click of a specific column of a datagrid table of material ui?
Asked Answered
B

1

8

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: enter image description here

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,
};
Beckon answered 27/10, 2021 at 18:18 Comment(0)
B
15

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.

Bufflehead answered 27/10, 2021 at 19:36 Comment(3)
Thanks! Any idea how to modify onCellClick function handler to change the cell mode to 'edit'. For some reason the useDataApiRef hook does not work.Delamare
How do we listen to onclick only for a specific cell, for example 'age' in your example?Tollefson
@Tollefson to listen for a specific cell just use an if inside handleOnCellClick. Something like: if(params.field === '<FieldName>'){Mario

© 2022 - 2024 — McMap. All rights reserved.