How to hide button after pressing in material-table

736 views Asked by At

I am using react material-table. I am in need of a feature like this: I use remote data mode to get a list of records, then I use the custom column rendering function to add a Material Button at the end of each row in the table, When the user presses this button I want it to be hidden. How can I do that. I look forward to receiving your help.

This is the illustration image

1

There are 1 answers

2
NicoE On

I made this example, on button click it gets disabled and a variable is set to to a loading state:

enter image description here

The key aspect here is to define something that identifies the row that is being updated. I use an extra column on which you could also display a spinner component:

{
  field: "isUpdating",
  render: (rowdata) =>
    fetchingClient === rowdata.name
      ? "loading.." // Add your  <Spinner />
      : null
},

Since you want to render the button as a custom column (other way could be using actions), on the render attribute of that column, you can use rowdata parameter to access what you are looking for:

{
  field: "join",
  sorting: false,

  render: (rowdata) => (
    <button
      disabled={fetchingClient === rowdata.name}
      onClick={(event) => fetchDataFromRemote(rowdata.name)}
    >
      Go fetch
    </button>
  )
}

Here is the link to the sandbox and the complete code, I hope this works for you!

import React, { Fragment, useState } from "react";
import MaterialTable from "material-table";

export default function CustomEditComponent(props) {
const [fetchingClient, setFetchingClient] = useState("");

const fetchDataFromRemote = (clientName) => {
    console.log(clientName);
    setFetchingClient(clientName);
};
const tableColumns = [
    { title: "Client", field: "client" },
    { title: "Name", field: "name" },
    {
    field: "isUpdating",
    render: (rowdata) =>
        fetchingClient === rowdata.name
        ? "loading.." // Add your  <Spinner />
        : null,
    },
    {
    field: "join",
    sorting: false,
    render: (rowdata) => (
        <button
        disabled={fetchingClient === rowdata.name}
        onClick={(event) => fetchDataFromRemote(rowdata.name)}
        >
        Go fetch
        </button>
    ),
    },
];

const tableData = [
    {
    client: "client1",
    name: "Jasnah",
    year: "2019",
    },
    {
    client: "client2",
    name: "Dalinar",
    year: "2018",
    },
    {
    client: "client3",
    name: "Kal",
    year: "2019",
    },
];

return (
    <Fragment>
    <MaterialTable
        columns={tableColumns}
        data={tableData}
        title="Material Table - custom column  "
        options={{ search: false }}
    />
    </Fragment>
);
}