Avinash
Avinash

Reputation: 426

how to set onClick event on a button inside a datatable in ReactJS

I have seen several working examples in jQuery but none in the context of React. So wanted this specific query raised.

I have a react Component Class which renders a datatable (as in datatables.net). I have added a View Button for each row in the datatable using column:defaultContent of datatable-Options.

I have written a class Method which is supposed to execute when the view Button is pressed.

The embedded HTML in columnDefault Option is

                columns: [
                  { "defaultContent":`<button onClick=${this.onView}>View</button>`},
                  { data: "name" },
                  { data: "email" },
                  { data: "mobile", "defaultContent": "<i>Not set</i>" },
                  { data: "landline", "defaultContent": "<i>Not set</i>"}
                ]

I can see that the Buttons are rendered.

The challenge is to get the onView method to execute with the specific recordId.

Upvotes: 1

Views: 4054

Answers (3)

awaisjavaid390
awaisjavaid390

Reputation: 1

  columns: [
    { data: 'Column 3' },
    {
      data: null,
      searchable: false,
      orderable: false,
      render: function(data, type, full, meta) {
        return '';
      },
    },
  ],
  columnDefs: [
    { targets: 3, createdCell: (td, cellData, rowData, row, col) => ReactDOM.render(
      <button className="btn btn-warning" style={{borderRadius: '30px'}} onClick={changeName}></button>,
      data,
      td)
    },
  ],

Upvotes: 0

Thanushka
Thanushka

Reputation: 411

My solution

   "columns": [
                   {
                       "data": "Column 1",
                   },
                   {
                       "data": "Column 2",
                   },
                   {
                       "data": "Column 3",
                   },
                   {
                       "data": null,
                       "searchable": false,
                       "orderable": false,
                       "render": function (data, type, full, meta) {
                           return ''
                       }
                   },
               ], 
 "columnDefs": [
                   {
                       targets: 3,
                       createdCell: (td, cellData, rowData, row, col) =>
                         ReactDOM.render(
                           <button className="btn btn-warning" style={{borderRadius: '30px'}}
                             onClick={changeName}>
                            data
                           </button>, td),
                     } 
               ]
    const changeName = async (e) => {
        alert('ok')
    }

Upvotes: 0

Tayyab Razzaq
Tayyab Razzaq

Reputation: 461

if you want to pass data to the callback function which is bind to onclick of button you can use below mentioned code

<button onClick=${() => this.onView(recordId)}>View</button>

Upvotes: 2

Related Questions