reactjsgridjs

Gridjs-react: Sort by column having a React Component


I'm using gridjs-react to create a custom grid as follows:

import { Grid, _ } from 'gridjs-react';

const tableData = [
  ['John', 12345, _(<input type="checkbox" name="ch" value="1" disabled checked />)],
  ['Mike', 67891, _(<input type="checkbox" name="ch" value="2" disabled />)],
]

export default function myCustomGrid() {
  return (
    <Grid
      sort
      columns={['Name', 'Phone', 'Checkbox']}
      data={tableData}
      pagination={{
        enabled: true,
        limit: 5,
      }}
    />
  );
}

The output is a table that contains 2 rows, It can be sorted by "Name" and "Phone". However It cannot be sorted by the "Checkbox" column that has <input> or any other React Component.

I ultimately want to be able to sort the table depending on whether the checkbox is checked or disabled or by its value if possible.


Solution

  • I've found the solution:

    import { Grid, _ } from 'gridjs-react';
    
    const tableData = [
      ['John', 12345, true],
      ['Mike', 67891, false],
    ]
    
    export default function myCustomGrid() {
      return (
        <Grid
          sort
          columns={[
            'Name', 
            'Phone', 
            {
              name: 'Enabled', 
              formatter: (isEnabled) => _(renderEnabled(isEnabled)) 
            }
          ]}
          data={tableData}
          pagination={{
            enabled: true,
            limit: 5,
          }}
        />
      );
    }
    
    const renderEnabled = (isEnabled) => {
      switch (isEnabled) {
        case true:
          return <input type="checkbox" disabled checked />;
        case false:
          return <input type="checkbox" disabled />;
        default:
          return <b>Dunno</b>;
      }
    };