Reputation: 839
I am currently using Material-UI data tables and have a search routine that is similar to this Codesandbox example, which is just searching on the Name/Food
column alone.
My current code is as follows:
const [filterFn, setFilterFn] = useState({ fn: items => { return items; } })
const handleSearch = e => {
let target = e.target;
setInput(target.value)
setFilterFn({
fn: items => {
if (target.value == "")
return items;
else
return items.filter(x => x.name.toLowerCase().includes(target.value))
}
})
}
And within my current search input, I am calling handleSearch
as follows:
<Controls.Input
id="name"
label="Search Name"
value={input}
autoFocus={true}
className={classes.searchInput}
InputProps={{
startAdornment: (<InputAdornment position="start">
<Search />
</InputAdornment>)
}}
onChange={handleSearch}
/>
With this, I now need a means of being able to search on any of the columns within this data table, i.e, Calories
, Carbs
or Protein
and not just on the Food
.
I was thinking of proving the user a drop-down selection list of all the available columns and then being able to use that column to perform their search but unsure how to achieve this as new to material-ui.
Can anyone please assist with how to achieve this or possibly point me to examples or other packages that still use material-ui as keen to get this going.
Upvotes: 0
Views: 2514
Reputation: 2504
Here's the similar case. Material-UI XGrid multiple select with checkbox 'select all rows checkbox' to select filtered rows only?
And if you can look through the applyFilter
function, then I am pretty sure that you could implement what you want by comparing searchedVal
inside a loop of keys.
That's an idea for it.
So in your case, I'd like to code this way.
const requestSearch = (originalRows: [], searchedVal: string): [] => {
return originalRows.filter((row) => {
let matches = true;
if (searchedVal) {
const properties = ['Name', 'Calories', 'Carbs', 'Protein'];
// include keys what you want to search
let containsVal = false;
properties.forEach((property) => {
if (originalRows[property].toLowerCase().includes(searchedVal.toLowerCase())) {
containsVal = true;
}
});
if (!containsVal) {
matches = false;
}
}
return matches;
});
};
I believe this is not tricky for Material-UI, just a search function in JavaScript.
Upvotes: 1