I have a action button in each row of my ag grid. I am using CellRenderer to show the button. Individual button clicks are working fine. But I want to programmatically trigger the click event for all button on click of another button. To batch process multiple rows. Is that possible?
Main Grid
const GridDemo = () => {
const gridRef = useRef();
const [rowData, setRowData] = useState();
const columnDefs = [
{
field: 'make',
filter: true,
cellRenderer: ButtonRenderer
},
{ field: 'model', filter: true },
{ field: 'price' }
];
// DefaultColDef sets props common to all Columns
const defaultColDef = useMemo(() => ({
sortable: true
}), []);
// Example load data from server
useEffect(() => {
fetch('https://www.ag-grid.com/example-assets/row-data.json')
.then(result => result.json())
.then(rowData => setRowData(rowData))
}, []);
const handleClick =() => { }
return (
<>
<button onClick={handleClick}>Click All</button>
<div className="ag-theme-alpine" style={{ width: 500, height: 500 }}>
<AgGridReact
ref={gridRef} // Ref for accessing Grid's API
rowData={rowData} // Row Data for Rows
columnDefs={columnDefs} // Column Defs for Columns
defaultColDef={defaultColDef} // Default Column Properties
/>
</div>
</>
);
};
Button Renderer
const ButtonRenderer = (props) => {
const clickHandler = () => {
console.log('Clicked!!!')
};
return (
<button onClick={clickHandler}>click</button>
)
}
export default ButtonRenderer
You can use the api method getCellRendererInstances
to get the cell renderer instances for the desired column, on which you can call your clickHandler
function. Please note:
Note that this method will only return instances of the cell renderer that exists. Due to row and column virtualisation, renderers will only exist for cells that the user can actually see due to horizontal and vertical scrolling.
Update your handleClick
function to the following:
const handleClick = () => {
const instances = gridRef.current.api.getCellRendererInstances();
instances.forEach((x) => {
x.clickHandler();
});
console.log(gridRef);
};
Demo.