Below is an example of cell renderer:
export default props => {
const cellValue = props.valueFormatted ? props.valueFormatted : props.value;
const buttonClicked = () => {
alert(`${cellValue} medals won!`)
}
return (
<span>
<span>{cellValue}</span>
<button onClick={() => buttonClicked()}>Push For Total</button>
</span>
);
}
The example below shows a simple Cell Renderer in action. It uses a Cell Renderer to render a hash (#
) symbol for each medal won
(instead of the medal count), and the MedalCellRenderer
defined in the code snippet above for the Total
column:
When a React component is instantiated the grid will make the grid APIs, a number of utility methods as well as the cell &
row values available to you via props
.
The interface for values available on both the initial props
value, as well as on future props
updates or subsequent refresh
calls
(see below for details on refresh
) are as follows:
Properties available on the ICellRendererParams<TData = any, TValue = any, TContext = any>
interface.
valueTypeTValue | null | undefined | Value to be rendered. |
value | Formatted value to be rendered. |
full | True if this is a full width row. |
pinnedType"left" | "right" | null | Pinned state of the cell. |
dataTypeTData | undefined | The row's data. Data property can be undefined when row grouping or loading infinite row models. |
nodeTypeIRowNode | The row node. |
row | The current index of the row (this changes after filter and sort). |
col | The cell's column definition. |
columnTypeColumn | The cell's column. |
e | The grid's cell, a DOM div element. |
e | The parent DOM item for the cell renderer, same as eGridCell unless using checkbox selection. |
get | Convenience function to get most recent up to date value. |
set | Convenience function to set the value. |
format | Convenience function to format a value using the column's formatter. |
refresh | Convenience function to refresh the cell. |
register | registerRowDragger:
rowDraggerElement The HTMLElement to be used as Row Dragger
dragStartPixels The amount of pixels required to start the drag (Default: 4)
value The value to be displayed while dragging. Note: Only relevant with Full Width Rows.
suppressVisibilityChange Set to true to prevent the Grid from hiding the Row Dragger when it is disabled.
|
apiTypeGridApi | The grid api. |
column | The column api. |
contextTypeTContext | Application context as set on gridOptions.context . |
See the section registering custom components for details on registering and using custom Cell Renderers.
Component Refresh needs a bit more explanation. Here we go through some of the finer details.
When the grid can refresh a cell (instead of replacing it altogether) then the update will occur as follows:
componentWillReceiveProps
, getDerivedStateFromProps
will get called and the function re-rendered.The grid can refresh the data in the browser, but not every refresh / redraw of the grid results in the refresh of your cell renderer.
The following items are those that do cause refresh to be called:
rowNode.setDataValue(colKey, value)
to set a value directly onto the rowNode
. This is the preferred API way to change one value from outside the grid.api.refreshCells()
to inform grid data has changed (see Refresh).If any of the above occur and the grid confirms the data has changed via Change Detection, then the Cell Renderer is refreshed.
The following will not result in the cell renderer's refresh method being called:
rowNode.setData(data)
to set new data into a rowNode
. When you set the data for the whole row, the whole row in the DOM is recreated again from scratch.All the above will result in the component being destroyed and recreated.
If you choose to implement the refresh
method, then note that this method returns a boolean value. If you do not
want to handle the refresh in the cell renderer, just return false
from an otherwise empty method. This will
indicate to the grid that you did not refresh and the grid will instead destroy the component and create another instance of your component from scratch instead.
As mentioned in the section on Change Detection, the refresh of the Cell will not take place if the value getting rendered has not changed.
The lifecycle of the cell renderer is as follows:
refresh()
is called, 0...n times (i.e. it may never be called, or called multiple times).In other words, component instantiation and destruction are always called exactly once. The component's GUI will
typically get rendered once unless the component is destroyed first. The component's props are updated/refresh()
is optionally called multiple times.
The diagram below (which is taken from the section Cell Content) summarises the steps the grid takes while working out what to render and how to render.
In short, a value is prepared. The value comes using either the colDef.field
or the colDef.valueGetter
. The value is also optionally passed through a colDef.valueFormatter
if it exists. Then the value is finally placed into the DOM, either directly, or by using the chosen colDef.cellRenderer
.
On top of the parameters provided by the grid, you can also provide your own parameters. This is useful if you want to 'configure' your Cell Renderer. For example, you might have a Cell Renderer for formatting currency but you need to provide what currency for your cell renderer to use.
Provide params to a cell renderer using the colDef option cellRendererParams
.
// define cellRenderer to be reused
const ColourCellRenderer = props => <span style={{color: props.color}}>{props.value}</span>;
const GridExample = () => {
// other properties & methods
const [columnDefs] = useState([
{
headerName: "Colour 1",
field: "value",
cellRenderer: ColourCellRenderer,
cellRendererParams: {
color: 'guinnessBlack'
}
},
{
headerName: "Colour 2",
field: "value",
cellRenderer: ColourCellRenderer,
cellRendererParams: {
color: 'irishGreen'
}
}
]);
return (
<div className="ag-theme-alpine">
<AgGridReact
columnDefs={columnDefs}
...other properties
/>
</div>
);
};
Sometimes the data
property in the parameters given to a cell renderer might not be populated. This can happen for
example when using row grouping (where the row node has aggData
and groupData
instead of data
), or when rows are
being loaded in the Infinite Row Model and do not yet have data. It is best to check that data
does exist before accessing it in your cell renderer, for example:
// define cellRenderer to be reused
const CellRenderer = props => <span>{props.data ? props.data.theBoldValue : null}</span>;
The example below shows five columns formatted, demonstrating each of the methods above.
cellStyle
to format each cell in the column with the same style.The example below demonstrates how to implement a simple custom group cell renderer.
After the grid has created an instance of a cell renderer for a cell it is possible to access that instance. This is useful if you want to call a method that you provide on the cell renderer that has nothing to do with the operation of the grid. Accessing cell renderers is done using the grid API getCellRendererInstances(params)
.
An example of getting the cell renderer for exactly one cell is as follows:
// example - get cell renderer for first row and column 'gold'
const firstRowNode = gridOptions.api.getDisplayedRowAtIndex(0);
const params = { columns: ['gold'], rowNodes: [firstRowNode] };
const instances = gridOptions.api.getCellRendererInstances(params);
if (instances.length > 0) {
// got it, user must be scrolled so that it exists
const instance = instances[0];
}
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.
The example below demonstrates custom methods on cell renderers called by the application. The following can be noted:
MedalCellRenderer
. The cell renderer has an arbitrary method medalUserFunction()
which prints some data to the console.getCellRendererInstances()
method will return nothing if the grid is scrolled far past the first row showing row virtualisation in action.Note that the hook version of the above example makes use of useImperativeHandle
to expose methods to the grid (and other components). Please
refer to the hook specific documentation for more information.
This example illustrates a few different ideas:
ref
to access AgGridReact
in order to access the underlying APIsWhen using custom cell renderers, the custom cell renderer is responsible for implementing support for keyboard navigation among its focusable elements. This is why by default, focusing a grid cell with a custom cell renderer will focus the entire cell instead of any of the elements inside the custom cell renderer.
Adding support for keyboard navigation and focus requires a custom suppressKeyboardEvent
function in grid options. See Suppress Keyboard Events.
An example of this is shown below, enabling keyboard navigation through the custom cell elements when pressing Tab and Shift+Tab:
Natalie Coughlin
cell, press the Tab key and notice that the button, textbox and link can be tabbed into. At the end of the cell elements, the tab focus moves to the next cell in the next rowThe suppressKeyboardEvent
callback is used to capture tab events and determine if the user is tabbing forward or backwards. It also suppresses the default behaviour of moving to the next cell if tabbing within the child elements.
If the focus is at the beginning or the end of the cell children and moving out of the cell, the keyboard event is not suppressed, so focus can move between the children elements. Also, when moving backwards, the focus needs to be manually set while preventing the default behaviour of the keyboard press event.