I'm trying to implement a custom filter for material table.
The table data is:
[
{
name: "Tomato",
color: "red",
quantity: 12,
id: "01"
},
{
name: "Banana",
color: "yellow",
quantity: 5,
id: "02"
},
{
name: "Lemon",
color: "yellow",
quantity: 20,
id: ""
},
{
name: "Blueberry",
color: "blue",
quantity: 50,
id: ""
}
]
Columns:
[
{
title: "Name",
field: "name",
filterComponent: props => {
return (
<FormControlLabel
control={<Checkbox color="primary" />}
label="Custom filter"
labelPlacement="end"
/>
);
}
},
{ title: "Color", field: "color", filtering: false },
{ title: "Quantity", field: "quantity", filtering: false },
{ title: "Code", field: "code", filtering: false, hidden: true }
]
Link to code sandbox here
The checkbox filter I'm trying to implement has to hide/show all rows that have "id" property of an empty string.
To implement custom filtering, we need to alter data at our end. For that, I did the following changes
Define state hook for data & checkbox state
const [data, setData] = useState([...testData]);
const [checked, setChecked] = useState(false);
In
control
I calledfilterValue
with current action state(true or false
) of checkbox.
<FormControlLabel
control={<Checkbox checked={checked} color="primary" onChange={(e) => filterValue(e.target.checked) }/>}
label="Custom filter"
labelPlacement="end"
/>
I filter data based on the condition you mentioned(
id
should not be blank).
const filterValue = (value) => {
if(value) {
const filtered = data.filter(d => d.id.trim().length > 0);
setData(filtered) // set filter data if checkbox is checked
} else {
setData([...testData]) // else set original data i.e testData
}
setChecked(value)
}
In
MaterialTable
I replacedtestData
withdata
here.
<MaterialTable
columns={columns}
data={data}
options={{
filtering: true
}}
/>
working example https://codesandbox.io/s/unruffled-antonelli-gfqcg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.