How to use datatables.net in reactjs the proper way?

Viewed 2630

I'm trying to use datatables.net recently in reactjs, but I'm having a hard time converting jQuery into reactjs. I have tried documentation of datatables.net , but i couldn't get it to work properly, after all react return to use it's virtual Dom. which leads to problems.

I have tried this by using ref and load it in ComponentDidMount(), but I couldn't customize the table header, columns or use the full guided documentation.

import React, { Component } from 'react';
import dt from 'datatables.net-bs';

class DataTables extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data:  [
        {
          "id": "1",
          "name": "Tiger Nixon",
          "position": "System Architect",
          "salary": "$320,800",
          "start_date": "2011/04/25",
          "office": "Edinburgh",
          "extn": "5421"
        },
        {
          "id": "2",
          "name": "Garrett Winters",
          "position": "Accountant",
          "salary": "$170,750",
          "start_date": "2011/07/25",
          "office": "Tokyo",
          "extn": "8422"
        }
      ]
    };
  }

  componentDidMount() {
    this.$el = $(this.el);
    this.$el.DataTable = dt;
    this.$el.DataTable({
      data: this.state.data,
      columns: [
        { data: 'name', title: 'Name' },
        { data: 'position', title: 'Position' },
        { data: 'office', title: 'Office' },
        { data: 'extn', title: 'Extn' },
        { data: 'start_date', title: 'Start_date' },
        { data: 'salary', title: 'Salary' }
      ]
    });
  }

  componentWillUnmount() {
    $('.display')
      .find('table')
      .DataTable()
      .destroy(true);
  }

  render() {
    return (
      <div>
        <table className="display" width="100%" ref={el => this.el = el} />
      </div>
    );
  }
}

export default DataTables;

I get the table but I couldn't custom the table headers, columns or I don't know how to use onRowClick or select row, I get this in jQuery in documentation of datatables. But how to use it in react.

The expected result is to get an example of how to use datatables with react a fully functional table, row selection , on row click, cell edit, custom cell and custom column. an example to understand how to use any docs in datatable that is made for jQuery in react.

Note: I have searched a lot, and I know there is a lot of other libraries but I wanted to expand my experience on this one. To have better experience on using jQuery with reactjs

0 Answers
Related