4. Custom Cell Renderers and Editors
One of AG Grid's powerful features is the ability to entirely replace the default cell appearance or editing behavior with React components using Custom Cell Renderers and Cell Editors. This allows for flexible adaptation to complex UI requirements.
4.1. Implementing Custom Cell Renderers
To customize the content of cells in a specific column, assign a React component to the cellRenderer property. This component will be used by the grid to render the cell's data.
// MyButtonRenderer.js
import React from 'react';
export default ({ value, data }) => {
const buttonClicked = () => {
alert(\`Row data: \${JSON.stringify(data)}\`);
};
return <button onClick={buttonClicked}>Click: {value}</button>;
};
// columnDefs example:
{
headerName: "Action",
field: "valueField",
cellRenderer: 'MyButtonRenderer' // Specify component name
}
// frameworkComponents prop of AgGridReact component:
<AgGridReact
// ...
frameworkComponents={{ MyButtonRenderer }}
></AgGridReact>
4.2. Implementing Custom Cell Editors
To customize cell editing functionality, assign a React component to the cellEditor property. This component will appear when a user edits a cell.
// MySelectEditor.js (Example: Dropdown editor)
import React, { useState, forwardRef, useImperativeHandle } from 'react';
export default forwardRef((props, ref) => {
const [value, setValue] = useState(props.value);
useImperativeHandle(ref, () => {
return {
getValue() {
return value;
}
};
});
return (
<select value={value} onChange={e => setValue(e.target.value)}>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
);
});
// columnDefs example:
{
headerName: "Gender",
field: "gender",
editable: true,
cellEditor: 'MySelectEditor' // Specify custom editor
}
// Add MySelectEditor to frameworkComponents
Note: To connect custom components to AgGridReact, you must use the frameworkComponents prop.