javascriptreactjsnext.jsantd

Toggle a spinner on button click inside an antd table row


I have a table like this with a column that contains a button like this:

const columns = [
...
  {
    title: "button",
    dataIndex: "key",
    render: (text, record) => {
      return (
        <Button
          icon={<DeleteOutlined />}
          onClick={() => pendingToggle()}
        ></Button>
      );
    }
  }
];

When you click on this button it should swap the button with <Spin /> from ant design only on that row it is clicked. I have written a piece of code but it doesn't work you can find it here !

How can I do it?


Solution

  • You need to use React states so that the DOM gets re-rendered. To do so, you need a react component, something like:

    function ButtonCell() {
      const [pending, setPending] = useState(false);
    
      return pending ? (
        <Spin />
      ) : (
        <Button icon={<DeleteOutlined />} onClick={() => setPending(true)}>
          Delete
        </Button>
      );
    }
    

    In your table you can type:

    {
      title: "button",
      dataIndex: "key",
      render: () => {
        return <ButtonCell />;
      } // or just `render: ButtonCell`
    }
    

    Working example:

    Edit ant.design (forked)