A. L
A. L

Reputation: 12649

DataTables - Calling functions in 'columnDefs' in react

So when I'm creating a DataTable in react, defining a certain column using the columnDefs property.

"columnDefs": [
            {
              "targets": 7,
              "data": "data",
              "render": function ( data, type, full, meta ) {
                return "<button onclick='test()'>view</button>"
              }
            }
          ]

But as expected, it can't find the test() function. Is there anyway to do this jsx style or something? Or will I just have to create the function inside the onclick?

Upvotes: 2

Views: 2690

Answers (3)

Akhilesh
Akhilesh

Reputation: 1313

You can use the arrow function and this object

"columnDefs": [
            {
              "targets": 7,
              "data": "data",
              "render": ( data, type, full, meta ) => {
                return "<button onclick='this.test()'>view</button>"
              }
            }
          ]

Upvotes: 0

Sachi Tekina
Sachi Tekina

Reputation: 1810

You can't use render in this case as the function will be called directly. You can use arrow function and createdCell insetead in columnDefs. For example you have a function in a component:

 this.test= this.test.bind(this);

Call that function in columnDefs by:

"columnDefs": [{
  "targets": 0,
  "data": "data",
  "createdCell": (td, cellData, rowData, row, col) => {
    $(td).click(e => {
      this.test();
    })
  }
}]

Take a look at the link above for more information.

Upvotes: 2

saf21
saf21

Reputation: 844

You can try like this:

$('#your_table').DataTable({

. . . 

"columnDefs": [{
                "targets": 7,
                "data": "data",
                "render": function ( data, type, full, meta ) {
                            return "<button class='view_btn' data-id='"+data+"'>view</button>"
                          }
              }]

Then create the test function outside:

$('#your_table').on('click', '.view_btn', function(){
  var id = $(this).data('id');
  test(id); // your function
});

Upvotes: 2

Related Questions