---
title: "Expressions"
framework: react
version: "36.1.0"
---

# Expressions

Expressions can be used in two different ways as follows:

1. **Column Definition Expressions:** Inside column definitions instead of functions for `valueGetter`, `valueSetter`, `valueFormatter` and `valueParser`.
2. **Cell Expressions:** Inside cells within the grid, similar to placing expressions in cells in Excel.

## Column Definition Expressions

Expressions can be used inside column definitions instead of using functions for the getters, setters, formatters and parsers. To use an expression instead of a function, just put the body of the function into a string.

```jsx
const [columnDefs, setColumnDefs] = useState([
    // column definition using standard functions
    {
        field: 'employee',
        valueGetter: params => params.data.firstName,
        valueFormatter: params => params.value.toUpperCase(),
    },
    // column definition using expressions
    {
        field: 'manager',
        valueGetter: 'data.firstName',
        valueFormatter: 'value.toUpperCase()'
    }
]);

<AgGridReact columnDefs={columnDefs} />
```

## Example Column Definition Expressions

In this example string expressions are used instead of functions for `valueGetter`, `valueSetter`, `valueFormatter` and `valueParser`.

#### Column Definition Expressions

```tsx
("use client");

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  AutoSizeStrategy,
  CellValueChangedEvent,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnAutoSizeModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  NumberEditorModule,
  TextEditorModule,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  TextEditorModule,
  ColumnAutoSizeModule,
  ClientSideRowModelModule,
  NumberEditorModule,
];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    {
      headerName: "String (editable)",
      field: "simple",
      editable: true,
    },
    {
      headerName: "Number (editable)",
      field: "number",
      editable: true,
      valueFormatter: `"£" + Math.floor(value).toString().replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, "$1,")`,
    },
    {
      headerName: "Name (editable)",
      editable: true,
      valueGetter: 'data.firstName + " " + data.lastName',
      valueSetter:
        // an expression can span multiple lines!!!
        `var nameSplit = newValue.split(" ");
             var newFirstName = nameSplit[0];
             var newLastName = nameSplit[1];
             if (data.firstName !== newFirstName || data.lastName !== newLastName) {  
                data.firstName = newFirstName;  
                data.lastName = newLastName;  
                return true;
            } else {  
                return false;
            }`,
    },
    { headerName: "A", field: "a", width: 100 },
    { headerName: "B", field: "b", width: 100 },
    { headerName: "A + B", valueGetter: "data.a + data.b" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      sortable: false,
    };
  }, []);
  const autoSizeStrategy = useMemo<AutoSizeStrategy>(() => {
    return { type: "fitGridWidth" };
  }, []);

  const onCellValueChanged = useCallback((event: CellValueChangedEvent) => {
    console.log("data after changes is: ", event.data);
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            autoSizeStrategy={autoSizeStrategy}
            onCellValueChanged={onCellValueChanged}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Column Definition Expressions](https://www.ag-grid.com/examples/cell-expressions/column-definition-expressions/reactFunctionalTs)

## Variables to Expressions

The following variables are available to the expression with the following params mapping:

- `x` => params.value
- `value` => params.value
- `oldValue` => params.oldValue
- `newValue` => params.newValue
- `node` => params.node
- `data` => params.data
- `colDef` => params.colDef
- `column` => params.column
- `columnGroup` => params.columnGroup
- `getValue` => params.getValue
- `api` => params.api
- `ctx` => params.context

For example, for `valueFormatter`'s, you can access to the value via the 'x' and 'value' attributes. However in `valueGetter`'s, the 'x' and 'value' will be undefined as these are not part of the `valueGetter` params.

## Column Definition Expressions vs Functions

Expressions and functions are two ways of achieving identical results. So why have two methods?

The advantage of functions is that they are easier to work with for you. Functions will be treated by your IDE as functions and thus benefit from compile time checks, debugging etc.

The advantage of expressions is that they are more compact, and it keeps your column definitions as simple JSON objects (just strings, no functions) which makes them candidates for saving in offline storage (e.g. storing a report definition in a database).

> **Note**
>
> String based expressions are parsed and evaluated as JavaScript. Use of this form of expression may require configuration of your [Content Security Policy](https://www.ag-grid.com/react-data-grid/security/#content-security-policy-csp).
>
> Functions are recommended for most use cases, unless there is a specific need for string-based expressions.

## Cell Expressions

Above we saw how you can have `expressions` instead of `valueGetters`. A shortcoming of this approach is that the expression belongs to the column and cannot be defined as part of the data, or in other words, the expression is for the entire column, it cannot be set to a particular cell.

Cell Expressions bring the expression power to the cell level, so your grid can act similar to how spreadsheets work.

> **Note**
>
> Although you can put expressions into cells like Excel, the intention is that your application will decide what the expressions are. It is not intended that you give this power to your user and have the cells editable. This is because AG Grid is not trying to give Excel expressions to the user, rather AG Grid is giving you, the developer, the power to design reports and include JavaScript logic inside the cells.

To enable cell expressions, set `enableCellExpressions=true` in the gridOptions. Then, whenever the grid comes across a value starting with '=', it will treat it as an expression.

The cell expressions have the same parameters of value getter expressions.

Because you have access to the context (ctx) in your expression, you can add functions to the context to be available in your expressions. This allows you limitless power in what you can calculate for your expression. For example, you could provide a function that takes values from outside of the grid.

## Example Cell Expressions

This example demonstrates cell expressions. The second column values in the LHS (Left-Hand Side) grid all have expressions. The following can be noted:

- "Number Squared" and "Number x 2" both take the number from the header as an input.
- "Today's Date" prints the date.
- "Sum A" and "Sum B" both call a user provided function that is attached to the context (Note that "Sum A" and "Sum B" are using values from the RHS grid).

#### Cell Expressions

```tsx
'use client';
import React, { StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";

import type { ColDef, GridApi, GridReadyEvent } from "ag-grid-community";
import {
  ClientSideRowModelModule,
  HighlightChangesModule,
  NumberEditorModule,
  RenderApiModule,
  TextEditorModule,
  enableDevValidations,
} from "ag-grid-community";
import { AgGridProvider, AgGridReact } from "ag-grid-react";

import "./styles.css";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  RenderApiModule,
  TextEditorModule,
  HighlightChangesModule,
  ClientSideRowModelModule,
  NumberEditorModule,
];

interface LeftData {
  function: string;
  value: string;
}

interface RightData {
  a: number;
  b: number;
}

const rowDataLeft: LeftData[] = [
  { function: "Number Squared", value: "=ctx.theNumber * ctx.theNumber" },
  { function: "Number x 2", value: "=ctx.theNumber * 2" },
  { function: "Today's Date", value: "=new Date().toLocaleDateString()" },
  { function: "Sum A", value: '=ctx.sum("a")' },
  { function: "Sum B", value: '=ctx.sum("b")' },
];

// Kept module-level and mutated in place so both the grid and the sum() closure
// always read the same row-data array after an edit.
const rowDataRight: RightData[] = [
  { a: 1, b: 22 },
  { a: 2, b: 33 },
  { a: 3, b: 44 },
  { a: 4, b: 55 },
  { a: 5, b: 66 },
  { a: 6, b: 77 },
  { a: 7, b: 88 },
];

const context: { theNumber: any; sum: (field: keyof RightData) => number } = {
  theNumber: 4,
  sum: (field) => {
    let result = 0;
    rowDataRight.forEach((item) => {
      result += item[field];
    });
    return result;
  },
};

const leftColumnDefs: ColDef<LeftData>[] = [
  { headerName: "Function", field: "function", minWidth: 150 },
  { headerName: "Value", field: "value" },
  {
    headerName: "Times 10",
    valueGetter:
      'typeof getValue("value") === "number" ? getValue("value") * 10 : null',
  },
];

const leftDefaultColDef: ColDef = {
  flex: 1,
  sortable: false,
  enableCellChangeFlash: true,
};

const rightColumnDefs: ColDef<RightData>[] = [{ field: "a" }, { field: "b" }];

const GridExample = () => {
  const [leftApi, setLeftApi] = useState<GridApi | null>(null);

  // Tell the left grid to refresh when the number changes.
  const onNewNumber = (value: string) => {
    context.theNumber = new Number(value);
    leftApi?.refreshCells();
  };

  // Tell the left grid to refresh when the right grid values change.
  const rightDefaultColDef: ColDef = {
    flex: 1,
    width: 150,
    editable: true,
    onCellValueChanged: () => leftApi?.refreshCells(),
  };

  return (
    <AgGridProvider modules={modules}>
      <div className="example-wrapper">
        <div className="item-header">
          Enter a number to analyse:
          <input
            type="text"
            onInput={(e) => onNewNumber(e.currentTarget.value)}
          />
        </div>
        <div className="item-header">
          Edit data on RHS, table updates on LHS
        </div>
        <div className="grid-wrapper">
          <AgGridReact<LeftData>
            columnDefs={leftColumnDefs}
            defaultColDef={leftDefaultColDef}
            enableCellExpressions={true}
            rowData={rowDataLeft}
            context={context}
            onGridReady={(params: GridReadyEvent) => setLeftApi(params.api)}
          />
        </div>
        <div className="grid-wrapper">
          <AgGridReact<RightData>
            columnDefs={rightColumnDefs}
            defaultColDef={rightDefaultColDef}
            rowData={rowDataRight}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Cell Expressions](https://www.ag-grid.com/examples/cell-expressions/cell-expressions/reactFunctionalTs)

## How Expressions Work

When you provide an expression to the grid, the grid converts the expression into a function for you and then executes the function. Consider the example below, the example provides `data.firstName` as the expression. This snippet of code then gets wrapped into a function with all the params attributes as function attributes.

```js
// this is a simple expression on the column definition
colDef.valueGetter = 'data.firstName';

// the grid will then compile the above to this:
___compiledValueGetter = (node, data, colDef, column, api, ctx, getValue) => {
    return data.firstName;
}
```

If your expression has the word `return` in it, then the grid will assume it is a multi line expression and will not wrap it.

If your value getter does not have the word `return` in it, then the grid will insert the `return` statement and the `;` for you.

If your expression has many lines, then you will need to provide the `;` at the end of each line and also provide the `return` statement.
