Home > Software design >  How to use onClick in antd table to get target value?
How to use onClick in antd table to get target value?

Time:11-16

I have an antd table, where there is an expandable row. I want to render data based on the row that I click as each row has a unique code. How do I get the target value of the row so as to filter data accordingly?

<Table
  components={components}
  bordered
  dataSource={dataSource}
  columns={tableColumns}
  expandable={{ expandedRowRender,
  onClick: (e) =>findId( e.target.value),
}}

Do I use onRow? Not sure how onClick is used in antD table or an expandable table. I've also got

expandRowByClick: true,

enabled in the expandable. So I have two questions

  1. How can I expand the table by clicking only one particular cell
  2. When expanded, how can I capture the clicked row so that I can render data accordingly to the expanded table?

CodePudding user response:

Same as onRow, onHeaderRow, onCell, onHeaderCell

   <Table
  onRow={(record, rowIndex) => {
    return {
      onClick: event => { 
         console.log(record)
      }, // click row
      onDoubleClick: event => {}, // double click row
      onContextMenu: event => {}, // right button click row
      onMouseEnter: event => {}, // mouse enter row
      onMouseLeave: event => {}, // mouse leave row
    };
  }}
  onHeaderRow={(columns, index) => {
    return {
      onClick: () => {}, // click header row
    };
  }}
/>

if you want to click a button :

<Column
        title="title"
        dataIndex="cdcName"
        key="cdcName"
        render={(text, record)=><button onClick={(e)=> console.log(e)}>{record?.cdcName}</button>}
    />

CodePudding user response:

you have to set an action to get the record data of a row in a column.

for exemple :

    const tableColumns =  [
          { title: "id", dataIndex: "id", key: "id", sorter: true },
          {
            title: "Description",
            dataIndex: "description",
            key: "description",
            sorter: true
          },
          {
            title: "Action",
            dataIndex: "id",
            key: "id",
            align: "center",
            render: (text, record, index) => {
              return (
                
                  <Button
                    icon={<BsPencil />}
                    id={record.id}
                    onClick={e => console.log(e, record)}
           //record is the row data
                    size="large"
                    
                  />
    
                 
          
              );
            }
          }
        ];
    
    
    <Table
      components={components}
      // add this
      rowKey={(record) => record.id} 
      bordered
      dataSource={dataSource}
      columns={tableColumns}
      expandable={{ expandedRowRender,
      onClick: (e) =>findId( e.target.value),
    }}
  • Related