Search code examples
javascriptreactjsmaterial-uimaterial-table

Grab row data onclick of a field in material-table


import MaterialTable from "material-table";
import ShipmentContext from "../context/ShipmentContext";

const ItemsTable: React.FC = () => {
  const shipmentcontext = useContext(ShipmentContext);

  const { filtered } = shipmentcontext.State;

  return (
    <>
      <div style={{ width: "100%", overflowY: "hidden" }}>
        <MaterialTable
            options={{
            search: false,
            showTitle: false,
            toolbar: false,
            paging: false,
            padding: "dense",
            maxBodyHeight: "400px",
            minBodyHeight:"400px",
            paginationType: "stepped",
            tableLayout: "fixed"
          }}
          columns={[
            { title: "AWB NUMBER", field: "awbno" ,},
            { title: "TRANSPORTER", field: "carrier" },
            { title: "SOURCE", field: "from" },
            { title: "DESTINATION", field: "to" },
            { title: "BRAND", field: "carrier" },
            { title: "START DATE", field: "pickup_date" },
            { title: "ETD", field: "" },
            {
              title: "STATUS",
              field: "current_status",
              cellStyle: {
                color: "green",
              },
            },
          ]}
          data={filtered}
        />
      </div>
    </>
  );
};

export default ItemsTable;

I want to gather the data of the field i clicked on the row.As here the data is dynamic i am unable to make an onClick method to grab the object which is clicked in the row.

My table look like this :

table

I want an onClick method which when i click on any AWB number grabs the data of it


Solution

  • You can use the custom render function for that to add a custom onClick handler like this:

    columns={[
                { title: "AWB NUMBER", field: "awbno" , render: row => <div onClick={() => console.log(row.awbno)}>{row.awbno}</div>}, // This will be called if this cell is clicked
                { title: "TRANSPORTER", field: "carrier" },
                { title: "SOURCE", field: "from" },
                { title: "DESTINATION", field: "to" },
                { title: "BRAND", field: "carrier" },
                { title: "START DATE", field: "pickup_date" },
                { title: "ETD", field: "" },
                {
                  title: "STATUS",
                  field: "current_status",
                  cellStyle: {
                    color: "green",
                  },
                },
              ]}
    ```