Mui-Datatables custom filter for boolean values

171 views Asked by At

I have a set of data with a boolean variable of keywordFound. I want a check to appear in the table if this is true and a X if it is false. I also want filtering to work as expected on this field.

const testTableData: Array<any> = [
 {
    id: "1",
    keywordFound: true,
    name: "BEST TEST",
 },
 {
    id: "2",
    keywordFound: true,
    name: "UNLIMITED POWER",
 },
 {
    id: "3",
    keywordFound: false,
    name: "STAR OF DEATH",
 },
 {
    id: "4",
    keywordFound: false,
    name: "HOPE AND TRUTH",
 },
];


const tableColumns: Column[] = [
    {
        name: "id",
        label: "Id",
        options: {
            filter: false,
            sort: false,
            display: false
        }
    },
    {
        name: 'name',
        label: 'Name',
        options: {
            filter: false,
            sort: false,
            empty: false,
            display: true,
        }
    },
    {
        name: 'keywordFound',
        label: 'Keyword Found',
        options: {
            filter: true,
            sort: true,
            empty: false,
            display: true,
            filterType: 'checkbox',
            filterOptions: {
                names: ['Found', 'Not Found'],
                logic(active, filterVal, row) {
                    return active;
                },
            },
            customBodyRenderLite: (dataIndex) => {
                const value = testTableData[dataIndex].keywordFound;
                if (value == true) {
                    return (
                        <Stack direction='row'>
                            <Check color='success'/>
                        </Stack>
                    )
                } else {
                    return (
                        <Stack direction='row'>
                            <Clear color='error'/>
                        </Stack>
                    )
                }
            },
        },
    },
];

const tableOptions = {
  filter: true,
  filterType: 'checkbox',
  selectableRows: 'none',
  sort: true,
  viewColumns: true,
};

export default function DataTableComponent() {
 return (
   <TableContainer>
    <MUIDataTable
      data={testTableData}
      columns={tableColumns}
      options={tableOptions}
    />
   </TableContainer>
 )
}
0

There are 0 answers