Tuesday, May 29, 2018

ReactTable accessing the type definition

There are two ways to do that.

First approach, import all of the react-table.

import * as ReactTable from 'react-table';

class Something extends.ReactComponent<{}, {}>
{
   private table: ReactTable.Instance;

   public render(): React.ReactNode
   {
      return <>
          <ReactTable.default
             ...
          >
             {(state, makeTable, instance) =>
             {
                 this.table = instance;
                 return makeTable();
             }
          </ReactTable>
      <>;
   }
}

<ReactTable.default ...> is a leaky abstraction though. All the advances in adding syntactic sugars to TypeScript/ES6, and yet some devs still want to leak the abstraction, heretic! Might as well just use de-sugarized import:

const ReactTable = require('react-table');

   // now usage of .default is excusable

   <ReactTable.default


To avoid using the .default directly, just import ReactTable and its type definition separately

import ReactTable, * as ReactTableTypes from 'react-table';

class Something extends.ReactComponent<{}, {}>
{
   private table: ReactTableTypes.Instance;

   public render(): React.ReactNode
   {
      return <>
          <ReactTable
             ...
          >
             {(state, makeTable, instance) =>
             {
                 this.table = instance;
                 return makeTable();
             }
          </ReactTable>
      <>;
   }
}

That's cleaner, you can use ReactTable without the default property. This is possible though:

import ReactTable, * as ReactTableTypes from 'react-table';

class Something extends.ReactComponent<{}, {}>
{
   private table: ReactTableTypes.Instance;

   public render(): React.ReactNode
   {
      return <>
          <ReactTableTypes.default
             ...
          >
             {(state, makeTable, instance) =>
             {
                 this.table = instance;
                 return makeTable();
             }
          </ReactTable>
      <>;
   }
}


But who would do that?

No comments:

Post a Comment