Search code examples
javascriptreactjsreact-hookstabulator

Calling a tabulator table function in React


I am using Tabulator under React, with the react-tabulator module.

I am missing something very basic, likely due to my new knowledge of React. Implementing this module, I know how to connect a tabulator callback to a javascript function. But I don't know how to call a tabulator method. For instance:

  const options = {
    height: '100%',
    ajaxURL: 'http://example.com',
    ajaxProgressiveLoad: 'scroll',
    ajaxError: (error) => {
      console.log('ajaxError ', error);
    },
  };

...

      <ReactTabulator
        columns={columns}
        layout="fitColumns"
        data={[]}
        options={options}
      />

Here the ajaxError callback is passed to ReactTabulator, and called when appropriate.

Now, the tabulator module has lots of methods, for instance setData. Outside of React, this would be used as follows:

var table = new Tabulator("#example-table", {
    ajaxURL:"http://www.getmydata.com/now", //ajax URL
});

...

table.setData("http://www.getmydata.com/now");

How do I translate this into the React world (in a hook environment), since I don't have direct access to the equivalent of a 'table' object? Do I need to get to my tabulator object by using getElementById or something similar?


Solution

  • I believe that the solution is to use a ref as described here: https://reactjs.org/docs/refs-and-the-dom.html , in the section:

    Refs and Function Components

    By default, you may not use the ref attribute on function components because they don’t have instances:

    ...

    You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component:

    Using this approach I am able to access my tabulator setData method.

    const tableDisplay = (props) => {
      const tableRef = createRef();
    
      // I can now use setData in various effects:
      // if ((tableRef.current) && (tableRef.current.table)) {
      //    tableRef.current.table.setData();
    
      return (
          <ReactTabulator
            ref={tableRef}
            columns={columns}
            layout="fitColumns"
            data={[]}
            options={options}
          />
      );
    };
    

    This works just fine, I am just not sure this is the "clean" way to go about it?