I am trying to set a filter from outside the mui-datatable. I would like to pass in the value of the filter from actions outside of the table. For example click a button which has a preset filter. Is there an api to take an external event and change the filter state of the table?
...
const options = {
filter: true,
selectableRows: 'multiple',
filterType: 'dropdown',
responsive: 'vertical',
rowsPerPage: 10,
//* pass filter somehow here
receiveSomeFilter:this.state.tableFilter
};
const ageFilter = (age)=> {
this.setState({tableFilter:age})
}
return (
<div>
<Button onClick = {ageFilter(28)}>Filter by age 28</Button>
<MUIDataTable title={"ACME Employee list"} data={data} columns={columns} options={options} />
</div>
);
}
}
export default Example;
You can set up filtering from the outside by updating the options for each column, and updating the filterList
array of the column's options.
A simple example (CodeSandbox here)
import MUIDataTable from "mui-datatables";
import { Select, MenuItem } from "@material-ui/core";
import { useState } from "react";
export default function App() {
const initCols = [
{
name: "name",
label: "Name",
options: {
filterList: []
}
}
];
const [cols, setCols] = useState(initCols);
const [selectedFilter, setSelectedFilter] = useState("All");
const data = [
{ name: "Joey Tribbiani" },
{ name: "Phoebe Buffay" },
{ name: "Rachel Green" },
{ name: "Ross Geller" },
{ name: "Monica Geller" },
{ name: "Chandler Bing" }
];
const onFilter = ({ target: { value } }: any) => {
setSelectedFilter(value);
const filteredCols = [...cols];
let filterList = [];
if (value !== "All") {
filterList = [value];
}
// Target the column to filter on.
filteredCols[0].options.filterList = filterList;
setCols(filteredCols);
};
const options = {
filter: false
};
return (
<div className="App">
<Select onChange={onFilter} value={selectedFilter}>
<MenuItem value="All">All</MenuItem>
{data.map((x) => (
<MenuItem key={x.name} value={x.name}>
{x.name}
</MenuItem>
))}
</Select>
<MUIDataTable
title="Filter"
columns={cols}
data={data}
options={options}
/>
</div>
);
}
The key is in the onFilter
function, which is the onChange
listener for my external control (a Select in this case). You need to update the appropriate column's options.filterList
to an Array containing the exact value that a row might have for that column. That filterList
can contain multiple values, hence the Array. Set it an empty Array to remove filtering for that column. And of course you need to useState
to control the columns, otherwise it won't update.