Following Material-UI docs I've implemented a search filter on Datagrid table, but encoutered a problem there.
Search filter functionality works fine, but while clearing input value, table data doesn't update.
I tried to update personData
state if input value changes, but didn't help.
Here is the code and sandbox link
import ClearIcon from "@mui/icons-material/Clear";
import SearchIcon from "@mui/icons-material/Search";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import data from "./data.json";
import TextField from "@mui/material/TextField";
import { DataGrid } from "@mui/x-data-grid";
import React, { useState } from "react";
const columns = [
{ field: "name", headerName: "Name", flex: 1 },
{ field: "status", headerName: "Status", flex: 1 }
];
function escapeRegExp(value) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function QuickSearchToolbar(props) {
return (
<div>
<TextField
variant="standard"
value={props.value}
onChange={props.onChange}
placeholder="Search…"
InputProps={{
startAdornment: <SearchIcon fontSize="small" />,
endAdornment: (
<IconButton
title="Clear"
aria-label="Clear"
size="small"
style={{ visibility: props.value ? "visible" : "hidden" }}
onClick={props.clearSearch}
>
<ClearIcon fontSize="small" />
</IconButton>
)
}}
/>
</div>
);
}
const WindParkTable = () => {
const [searchText, setSearchText] = useState("");
const [personData, setPersonData] = useState(data || []);
const requestSearch = React.useCallback(
(searchValue) => {
setSearchText(searchValue);
const searchRegex = new RegExp(escapeRegExp(searchValue), "i");
const filteredRows = personData.filter((row) => {
return Object.keys(row).some((field) => {
return searchRegex.test(row[field].toString());
});
});
setPersonData(filteredRows);
},
[setPersonData, personData]
);
return (
<Box sx={{ height: 500, width: "100%", mt: "150px" }}>
{columns && (
<DataGrid
components={{ Toolbar: QuickSearchToolbar }}
rows={personData}
columns={columns}
componentsProps={{
toolbar: {
value: searchText,
onChange: (event) => requestSearch(event.target.value),
clearSearch: () => requestSearch("")
}
}}
/>
)}
</Box>
);
};
export default WindParkTable;
You are losing the original personData
when you call to setPersonData(filteredRows)
. You have to filter in data
instead of personData
in your WindParkTable
, something like this:
const filteredRows = data.filter((row) => {
return Object.keys(row).some((field) => {
return searchRegex.test(row[field].toString());
});
});