Search code examples
reactjsmaterial-table

Material Table Search doesn't work for custom column


Folks,

I have a mat table with a custom column as "Items" , this can have multiple values. I can render it as comma separated values however for better look and feel , I am rendering each item as chip.

Now the issue is mat table default search doesn't work on this field.

Any help would be greatly appreciated.

enter image description here

import React, { Fragment, useState } from "react";
import MaterialTable from "material-table";
import { Box, makeStyles, Chip } from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
    chip: {
      margin: 2
    },
    noLabel: {
      marginTop: theme.spacing(3)
    },
  }));
  

const originalData = [
  {
    id: "1",
    productName: "Meat",
    items: [
        {id : 1, name : "chicken"},
        {id : 2, name : "pork" },
        {id : 3, name : "lamb" }
        ]
    
  },
  {
    id: "2",
    productName: "Vegetables",
    items: [
        {id : 1, name : "Okra"},
        {id : 2, name : "Pumpkin" },
        {id : 3, name : "Onion" }
        ]
    
  },

];

export default function MatTableTest(props) {
  const [data, setData] = useState(originalData);
  const classes = useStyles();
  const tableColumns = [
    { title: "id", field: "id", editable : "never" },
    { title: "Product Name", field: "productName" , editable : "never" },
    { title: "Item", field: "items", editable : "never", 
    render: rowData => {
        return (
          <Box className="box" id="style-7">
            { rowData.items.map((exprt) => <Chip
              key={exprt.id}
              label={exprt.name}
              className={classes.chip}
            />)}
          </Box>
        );
      }
},

    
  ];

  return (
    <Fragment>
      <MaterialTable
        columns={tableColumns}
        data={data}
        title="Material Table - Custom Colum  Search"
      />
    </Fragment>
  );
}



Solution

  • There is a prop called customFilterAndSearch where you can define a custom filter function. You can define what row data you wish to match for in there. Here is an example from an issue created in Github repo.