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

# Configuration

Columns are configured using Column Definitions, manipulated with Column State and referenced using IDs or the Column Object.

## Defining Columns

Each column in the grid is defined using a [Column Definition](https://www.ag-grid.com/react-data-grid/column-definitions/), which is a JavaScript key-value object consisting of [Column Options](https://www.ag-grid.com/react-data-grid/column-properties/). An array of these objects can be passed to the `columnDefs` [Grid Option](https://www.ag-grid.com/react-data-grid/grid-options/#reference-columns-columnDefs) and the grid will create matching columns.

```jsx
const [columnDefs, setColumnDefs] = useState([
    { field: 'athlete' },
    { field: 'sport' },
    { field: 'age' }
]);

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

Columns can also be configured under [Column Groups](https://www.ag-grid.com/react-data-grid/column-groups/), which present the columns under shared headers. These can be configured by adding a level of nesting to the column definition.

```jsx
const [columnDefs, setColumnDefs] = useState([
    { field: 'athlete' },
    {
        headerName: 'Stats',
        children: [
            { field: 'sport' },
            { field: 'age' }
        ]
    }
]);

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

## Referencing Columns

Columns can be updated via the `columnDefs` grid option when a sufficient ID has been provided, or manipulated via the API with a Column Object.

### Column IDs

Every column in the grid will be given a unique ID to identify it. The ID can be provided explicitly via the `colId`. If the `colId` is omitted, the grid will try to use the `field` property. If neither of these are provided, the grid will generate a numeric column ID.

It is recommended to provide an explicit `colId` for any column that will be referenced elsewhere in the application.

In the example below, the column IDs are logged to the dev console. Note the following:

- Col 1 uses the `field`.
- Col 2 and 3 use the `colId`.
- Col 4 and Col 5 have neither `colId` or `field` so the grid generates column IDs.

#### Column IDs

```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 {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

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

const modules = [ColumnApiModule, ClientSideRowModelModule];

function createRowData() {
  const data = [];
  for (let i = 0; i < 20; i++) {
    data.push({
      height: Math.floor(window.agRandom() * 100),
      width: Math.floor(window.agRandom() * 100),
      depth: Math.floor(window.agRandom() * 100),
    });
  }
  return data;
}

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(createRowData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    // colId will be 'height',
    { headerName: "Col 1", field: "height" },
    // colId will be 'firstWidth',
    { headerName: "Col 2", colId: "firstWidth", field: "width" },
    // colId will be 'secondWidth'
    { headerName: "Col 3", colId: "secondWidth", field: "width" },
    // no colId, no field, so grid generated ID
    { headerName: "Col 4", valueGetter: "data.width" },
    { headerName: "Col 5", valueGetter: "data.width" },
  ]);

  const onGridReady = useCallback((params: GridReadyEvent) => {
    const cols = params.api.getColumns()!;
    cols.forEach((col) => {
      const colDef = col.getColDef();
      console.log(
        colDef.headerName + ", Column ID = " + col.getId(),
        JSON.stringify(colDef),
      );
    });
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={{ height: "100%", boxSizing: "border-box" }}>
          <div style={gridStyle}>
            <AgGridReact
              rowData={rowData}
              columnDefs={columnDefs}
              onGridReady={onGridReady}
            />
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

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

[Live example: Column IDs](https://www.ag-grid.com/examples/configuration/column-ids/reactFunctionalTs)

> **Warning**
>
> Column Ids should be unique across the grid. Where the provided `colId` or `field` are not unique, the grid will append `_n` where necessary (`n` being the first positive number that allows uniqueness). It is not recommended to rely on IDs generated with this behaviour.

### Column Objects

Every column displayed in the grid is represented by a [Column Object](https://www.ag-grid.com/react-data-grid/column-interface/#column) which has attributes, methods and events for interacting with the specific column e.g. `column.isVisible()`.

Columns can be accessed via Grid API methods, and provided as parameters from some [Grid Events](https://www.ag-grid.com/react-data-grid/grid-events/#reference-columns).

The [Column Reference](https://www.ag-grid.com/react-data-grid/column-object/) displays a list of functions available on the Column Object.

It is also possible to listen for [Column Events](https://www.ag-grid.com/react-data-grid/column-events/) by attaching an [Event Listener](https://www.ag-grid.com/react-data-grid/column-object/#reference-events-addEventListener).

Clicking on the `Log All Columns` and `Log All Column IDs` buttons will log the data to the developer console.

#### Column Object

```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 "./styles.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

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

const modules = [ColumnApiModule, ClientSideRowModelModule];

const GridExample = () => {
  const gridRef = useRef<AgGridReact>(null);
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>([
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxster", price: 72000 },
    { make: "BMW", model: "M50", price: 60000 },
    { make: "Aston Martin", model: "DBX", price: 190000 },
  ]);
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "make" },
    { field: "model" },
    { field: "price" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
    };
  }, []);

  const getAllColumns = useCallback(() => {
    console.log(gridRef.current!.api.getColumns());
  }, []);

  const getAllColumnIds = useCallback(() => {
    const columns = gridRef.current!.api.getColumns();
    if (columns) {
      console.log(columns.map((col) => col.getColId()));
    }
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="example-wrapper">
          <div style={{ marginBottom: "1rem" }}>
            <button onClick={getAllColumns}>Log All Columns</button>
            <button onClick={getAllColumnIds}>Log All Column IDs</button>
          </div>

          <div style={gridStyle}>
            <AgGridReact
              ref={gridRef}
              rowData={rowData}
              columnDefs={columnDefs}
              defaultColDef={defaultColDef}
            />
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

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

[Live example: Column Object](https://www.ag-grid.com/examples/configuration/column-object/reactFunctionalTs)

## Updating Columns

Columns can be controlled by updating the column state, or updating the column definition.

[Column State](https://www.ag-grid.com/react-data-grid/column-state/) should be used when restoring a users grid, for example saving and restoring column widths.

[Update Column Definitions](https://www.ag-grid.com/react-data-grid/column-updating-definitions/#changing-column-definition) to modify properties that the user cannot control, and as such are not supported by Column State. Whilst column definitions can be used to change stateful properties, this can cause additional side effects.
