LiveLoveApp logo

Cell Renderer Function

The cellRenderer function

  • After the value for a cell is determined, and we have optionally formatted the value, we can use a cell renderer to have full control of how a cell is rendered in AG Grid.
  • It's important to note that we should only use a cell renderer when necessary.
  • By default, the textContent of the cell HTML element is set to the (optionally formatted) value.
  • When we are using a cell renderer we are often adding additional elements, event listeners, etc. to the DOM, all of which must be rendered for each cell in the grid.

The cellRenderer for a column definition accepts the following values:

  1. undefined will render the cell's (optionally formatted) value as the textContent of the cell.
  2. A string that references a registered cell renderer.
  3. A React component

Before we dive into using the cellRenderer function, let's look at the CellRendererParams<TData, TValue> interface.

interface ValueFormatterParams<TData = any, TValue = any> {
  api: GridApi<TData>;
  colDef: ColDef<TData>;
  column: Column;
  columnApi: ColumnApi;
  context: any;
  data: TData | undefined;
  node: RowNode<TData> | null;
  value: TValue;
}

Let's look at an example of a cellRenderer function:

export default function Grid() {
  const [columnDefs] = useState<ColDef<RowData>[]>([
    {
      headerName: 'price',
      cellRenderer: (params) => {
        if (params.value === undefined) {
          return null;
        }
        return new Intl.NumberFormat('en-US', {
          style: 'currency',
          currency: 'USD',
        }).format(params.value);
      },
    },
  ]);
}

In the example, rather than using a valueFormatter for the Price field we are using a cellRenderer.

  • The cellRenderer function accepts the params object.
  • First, we check if the value is undefined.
  • Then, we invoke and return transformed value.

Exercise

The goal of this exercise is to learn how to use the cellRenderer function.

  1. Open the exercise on Stackblitz.
  2. Add a cellRenderer to the Date of Order column.
  3. First, check if the value is not undefined in the params object.
  4. Return JSX that includes a Material Icon next to the formatted date string.

Hint:

  • Render the icon using: <span className="material-icons">event</span>.

Solution

export default function Grid() {
  const [columnDefs] = useState<ColDef<RowData>[]>([
    {
      headerName: 'Date of Order',
      field: 'dateOfOrder',
      filter: 'agDateColumnFilter',
      cellRenderer: (params: ICellRendererParams) => {
        if (params.value === undefined) {
          return null;
        }
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span className="material-icons">event</span>
            {new Intl.DateTimeFormat('en-US').format(params.value)}
          </div>
        );
      },
    },
  ]);
}

See solution on Stackblitz