Reputation: 29
Question on ReactJS...
I need to have 2 ag-grids next to each other where the first one displays master records and the second one displays child records.
When a row is selected in the first ag-grid, the second ag-grid (which originally shows all child records) will filter down to display only the relevant child records pertaining to the selected master record in the first ag-grid table.
Example,
When page loads, table # 1 and table # 2 both show all countries and all metropolitan cities
When user clicks on, say, "India" in table # 1, the table # 2 will show the list of metropolitan cities in India only.
Some guidance in how to achieve this will be greatly appreciated.
Upvotes: 0
Views: 1511
Reputation: 2352
Suppose we have a parent component which renders two child grid components, the first grid for selecting a row and the second grid to filter based on the selected row.
In the parent component, provide a callback to the first grid component as props, so that the grid can notify the parent when the selected row has changed.
Also in the parent component, provide a prop value to the second grid component which receives the current selected row:
const GridExample = () => {
const [filter, setFilter] = useState(null);
return (
<div style={{ height: '100%', width: '100%', display: 'flex' }}>
<CountryGrid filterHasChanged={setFilter} />
<CityGrid currentFilter={filter} />
</div>
);
};
In the first grid, use the Grid Event onSelectionChanged
to know when a row has been selected, and then simply pass this selected row to the parent via the callback provided above:
const selectionChanged = (params) => {
const selectedRows = params.api.getSelectedRows()[0];
// create an object for the filterModel to be applied in the City Grid
const filterModel = {
country: {
values: [selectedRows.country],
},
};
props.filterHasChanged(filterModel);
};
Then inside the second grid, listen to the changes via a useEffect hook and call gridApi.setFilterModel
to set the filter whenever the selected row changes:
Documentation on Filter Models:
useEffect(() => {
if(props.currentFilter) {
gridApi.setFilterModel(props.currentFilter)
}
}, [props.currentFilter]);
See this implemented in the following sample.
Note: that the sample is not using a country / city dataset, however it shows the main principle of how you would go about achieving two grids communicating with each other.
Upvotes: 2