How do I add buttons to my Datatable in React.js

How do I add buttons to my Datatable in React.js

dougmdougm Posts: 28Questions: 4Answers: 0

I am new to React but have used datables a lot in a java application.

I want the same functionality in React.
I want to Add, Edit and Delete.
I am returning the data from my springboot application and it is the sample json data from one of your examples.
The data is displayed correctly but I can't figure out how to add the buttons.

Thanks,
Doug

import React, { Component } from "react";
import { Navigate } from "react-router-dom";
import AuthService from "../services/auth.service";
import EquipmentService from "../services/equipment.service";
import DataTable from 'datatables.net-react';
import DT from 'datatables.net-bs5';

DataTable.use(DT);

export default class Equipment extends Component {

  constructor(props) {
    super(props);
    this.state = {
      redirect: null,
      dataReady: false,
      finishedLoading: false,
      equipmentList: null,
      currentUser: { username: "" }
    };
  }

  componentDidMount() {
    console.log('equipment');
    const currentUser = AuthService.getCurrentUser();
    if (!currentUser) this.setState({ redirect: "/login" });
    EquipmentService.getEquipment(currentUser.customerId).then(
      data => this.setState({
        currentUser: currentUser,
        dataReady: true,
        finishedLoading: true,
        equipmentList: data
      })
    )

  }

  render() {
    const { equipmentList } = this.state;
    const { finishedLoading } = this.state;

    const columns = [
      { data: 'name' },
      { data: 'position' },
      { data: 'office' },
      { data: 'extn' },
      { data: 'start_date' },
      { data: 'salary' },
    ];

    if (this.state.redirect) {
      return <Navigate to={this.state.redirect} />
    }

    return (
      <div className="container">
        <br/>
        Equipment 
        {(this.state.finishedLoading) ?

          <div>

          <DataTable data={finishedLoading ? equipmentList.data : []} columns={columns} 
            options={{responsive: true, select: true,}} className="display" >
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Extn.</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </thead>
          </DataTable>
        </div>: null}
      </div>
    );
  }
}

Answers

  • kthorngrenkthorngren Posts: 21,554Questions: 26Answers: 4,994

    This blog has an example of loading the export buttons. Are you using the Editor for your Add, Edit and Delete buttons? You may want to look at this thread regarding loading the Editor.

    Kevin

  • dougmdougm Posts: 28Questions: 4Answers: 0

    Thanks Kevin. I tried using the editor but I couldn't get it installed.
    I get this error

    datatables_net_react__WEBPACK_IMPORTED_MODULE_3__.default.Editor is not a constructor
    I tried following the instructions but could not get it to work. Do I need a separate license?

    I now have the default buttons working thanks to the example, but I really want the Edit, Delete and Add button? Is there documentation somewhere? I have tried but just can't get it to work.

    Thanks

  • dougmdougm Posts: 28Questions: 4Answers: 0

    This is what I was trying with the Editor...

        const editor = new DataTable.Editor({
          data: finishedLoading ? equipmentList.data : [],
          fields: [
              {
                  label: 'Name:',
                  name: 'name'
              },
              {
                  label: 'Position:',
                  name: 'position'
              },
              {
                  label: 'Office:',
                  name: 'office'
              },
              {
                  label: 'Extension:',
                  name: 'extn'
              },
              {
                  label: 'Start date:',
                  name: 'start_date',
                  type: 'datetime'
              },
              {
                  label: 'Salary:',
                  name: 'salary'
              }
          ],
          table: '#example'
      });
    
      const table = new DataTable('#example', {
        data: finishedLoading ? equipmentList.data : [],
        columns: [
            {
                data: null,
                orderable: false,
                render: DataTable.render.select()
            },
            { data: 'name' },
            { data: 'position' },
            { data: 'office' },
            { data: 'start_date' },
            { data: 'salary', render: DataTable.render.number(null, null, 0, '$') },
            {
                data: null,
                defaultContent:
                    '<div class="action-buttons">' +
                    '<span class="edit"><i class="fa fa-pencil"></i></span> ' +
                    '<span class="remove"><i class="fa fa-trash"></i></span> ' +
                    '<span class="cancel"></span>' +
                    '</div>',
                className: 'row-edit dt-center',
                orderable: false
            }
        ],
        layout: {
            topStart: {
                buttons: [
                    { extend: 'create', editor: editor },
                    { extend: 'edit', editor: editor },
                    { extend: 'remove', editor: editor }
                ]
            }
        },
        order: [[1, 'asc']],
        select: {
            style: 'os',
            selector: 'td:first-child'
        }
    });
    
  • kthorngrenkthorngren Posts: 21,554Questions: 26Answers: 4,994

    I tried following the instructions but could not get it to work.

    What did you try? Make sure you are loading from a local resource.

    What versions of Datatables and Editor are you using?

    Do I need a separate license?

    Depends. The current version is 2.3.2. If you have a 2.x license then I don't believe you will need a separate license. If you have a license for 1.x then I believe you will need to purchase a new license for 2.x. See the Purchase and Download pages for details. If you don't have a 2. license then you should be able to download a 15 day trial.

    Is there documentation somewhere?

    I don't know of any specific Editor with React instructions.

    Kevin

  • dougmdougm Posts: 28Questions: 4Answers: 0

    React package.json

        "datatables.net-bs5": "^2.1.8",
        "datatables.net-buttons-dt": "^3.2.0",
        "datatables.net-dt": "^2.1.8",
        "datatables.net-editor-dt": "^2.2.0",
        "datatables.net-react": "^1.0.0",
        "datatables.net-select-dt": "^2.1.0",
    

    My javascript file from my spring mvc app says the following

    /**
     * @summary     DataTables Editor
     * @description Editing library for DataTables
     * @version     2.0.4
     * @file        dataTables.editor.js
     * @author      SpryMedia Ltd
     * @contact     www.datatables.net/contact
     */
    

    So are you saying to copy these to my React project and import them?

    Thanks
    Doug

  • kthorngrenkthorngren Posts: 21,554Questions: 26Answers: 4,994

    The key, I think, is Allan's comment in the thread I linked to:

    What you need to do is have the Editor Javascript and CSS files locally on your file system and to import editor from './vendors/editor/js/datatables.editor'; (or similar, depending on the path you use).

    The Editor will only run if its loaded from a local resource. The error you are getting is many times due to people trying to load Editor via CDN, etc. This is how the licensing is enforced as you will need to download a licensed copy using your ID once the trial expires.

    I don't know what you need to do specific to React. @allan can provide more specifics if needed.

    Kevin

  • allanallan Posts: 63,812Questions: 1Answers: 10,516 Site admin

    The easiest option is to use the Editor npm repository on our private registery.

    Editor 2.0.4 isn't available via that package though - I think it was around 2.1 or 2.2 that I introduced that. I don't think 2.0.4 had an ESM file either. If your project is setup for it, you could perhaps include the 2.0.4 CommonJS / UMD file, but I suspect it would be easier to use the ESM via NPM.

    Allan

  • dougmdougm Posts: 28Questions: 4Answers: 0

    Thanks for your help. I have decided to switch gears as I kept running into road blocks.

Sign In or Register to comment.