# Infinite Table API

Canonical page: https://infinite-table.com/docs/reference/api/

When rendering the `InfiniteTable` component, you can get access to the API by getting it from the [`onReady`](https://infinite-table.com/docs/reference/infinite-table-props.md#onReady) callback prop.

```tsx {2}
const onReady = (
  {api, dataSourceApi}: {
    api: InfiniteTableApi<DATA_TYPE>,
    dataSourceApi: DataSourceApi<DATA_TYPE>
  }) => {
  // api is accessible here
  // you may want to store a reference to it in a ref or somewhere in your app state
}

<InfiniteTable<DATA_TYPE>
  columns={[...]}
  onReady={onReady}
/>
```

For API on row/group selection, see the [Selection API page](https://infinite-table.com/docs/reference/selection-api).

See the [Infinite Table Cell Selection API page](https://infinite-table.com/docs/reference/cell-selection-api/index.md) for the cell selection API.
See the [Infinite Table Column API page](https://infinite-table.com/docs/reference/column-api/index.md) for the column API.
See the [Infinite Table Keyboard Navigation API page](https://infinite-table.com/docs/reference/keyboard-navigation-api/index.md) for the keyboard navigation API.

See the [Infinite Table Row Details API page](https://infinite-table.com/docs/reference/row-detail-api/index.md) for the row detail API (when master-detail is configured).
See the [Tree API page](https://infinite-table.com/docs/reference/tree-api/index.md) for the tree API (when using the `<TreeDataSource />` component).

### confirmEdit (`(value?: any) => void`)

> Confirms the current edit operation and closes the editor.

If the `value` parameter is provided, it will be used as the value the cell will be updated with. If the `value` parameter is not provided, the current value of the cell will be used.

See related [`cancelEdit`](https://infinite-table.com/docs/reference/api/index.md#cancelEdit) and [`rejectEdit`](https://infinite-table.com/docs/reference/api/index.md#rejectEdit).

### cancelEdit (`() => void`)

> Cancels the current edit operation and closes the editor.

See related [`confirmEdit`](https://infinite-table.com/docs/reference/api/index.md#confirmEdit) and [`rejectEdit`](https://infinite-table.com/docs/reference/api/index.md#rejectEdit).

### hideContextMenu (`() => void`)

> Hides the context menu that's currently displayed (if there's one).

### rejectEdit (`(error: Error) => void`)

> Rejects the current edit operation with the specified error and closes the editor.

The error will later be available to the [`columns.renderValue`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.renderValue) callback prop, via the parameter of the function (also applicable for related functions that are called with same the same parameter).

See related [`confirmEdit`](https://infinite-table.com/docs/reference/api/index.md#confirmEdit) and [`cancelEdit`](https://infinite-table.com/docs/reference/api/index.md#cancelEdit).

### clearColumnFilter (`(columnId: string) => void`)

> Clears any filter for the specified column

### toggleSortingForColumn (`(columnId: string, options?) => void`)

> Toggles the sorting for the specified column.

This is the same method the component uses internally when the user clicks a column header.

If the column is not sorted, it gets sorted in ascending order.

If the column is sorted in ascending order, it gets sorted in descending order.

If the column is sorted in descending order, the sorting is cleared.

The `options` is optional and can have the `multiSortBehavior` property, which can be either `append` or `replace`. See related [`multiSortBehavior`](https://infinite-table.com/docs/reference/infinite-table-props.md#multiSortBehavior) prop. If not provided, the default behavior is used.

See related [`setSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#setSortingForColumn) and [`getSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#getSortingForColumn).

### setSortingForColumn (`(columnId: string, dir: 1|-1|null) => void`)

> Sets the sorting for the specified column.

The sort direction is specified by the `dir` parameter, which can be:

- `1` for ascending
- `-1` for descending
- `null` for clearing the sorting.

See related [`toggleSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#toggleSortingForColumn) and [`getSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#getSortingForColumn).

### getSortingForColumn (`(columnId: string)=> 1|-1|null`)

> Returns the sorting currently applied to the specified column.

The return value is:

- `1` for ascending
- `-1` for descending
- `null` for no sorting.

See related [`toggleSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#toggleSortingForColumn) and [`setSortingForColumn`](https://infinite-table.com/docs/reference/api/index.md#setSortingForColumn).

### collapseGroupRow (`(groupKeys: any[]) => boolean`)

> Collapses the specified group row. Returns true if the group was expanded and is now being collapsed.

```tsx
api.collapseGroupRow(['USA', 'New York']); // collapses the group with these keys
```

### expandGroupRow (`(groupKeys: any[]) => boolean`)

> Expands the specified group row. Returns true if the group was collapsed and is now being expanded.

```tsx
api.expandGroupRow(['USA', 'New York']); // expands the group with these keys
```

### getCellValue (`({columnId, rowIndex?, primaryKey? }) => any`)

> Returns the value for the specified cell. The value is either the raw value (as retrieved via the `field` property of the column or by calling the column [valueGetter](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.valueGetter)) or the formatted value - if the column has a [valueFormatter](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.valueFormatter).

Call this function with an object that has a `columnId` and either a `rowIndex` or a `primaryKey` property.

See related [`getCellValues`](https://infinite-table.com/docs/reference/api/index.md#getCellValues).

This function should not be called during a cell render (eg: in [`columns.render`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.render)/[`columns.renderValue`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.renderValue) or other functions called during render).

### getCellValues (`({columnId, rowIndex?, primaryKey? }) => ({value, rawValue, formattedValue })`)

> Returns an object with raw and formatted values for the specified cell.

Call this function with an object that has a `columnId` and either a `rowIndex` or a `primaryKey` property.

The returned object has the following properties:

- `rawValue` - the raw value of the cell - as retrieved from the [`columns.field`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.field) property of the column or by calling the column [valueGetter](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.valueGetter)
- `formattedValue` - the formatted value of the cell - if the column has a [valueFormatter](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.valueFormatter), it's the value returned by the formatter, otherwise it's the same as the `rawValue`
- `value` - it's either `formattedValue` or `rawValue`. If the column has a [valueFormatter](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.valueFormatter), it's the value returned by the formatter, otherwise it's the `rawValue`

See related [`getCellValue`](https://infinite-table.com/docs/reference/api/index.md#getCellValue).

This function should not be called during a cell render (eg: in [`columns.render`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.render)/[`columns.renderValue`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.renderValue) or other functions called during render).

### getColumnApi (`(colIdOrIndex: string|number) => InfiniteTableColumnAPI`)

> Returns [a column API object](https://infinite-table.com/docs/reference/column-api/index.md) bound to the specified column

The parameter can be either a column id or a column index (note this is not the index in all columns, but rather the index in current visible columns).

### getVerticalRenderRange (`() => { renderStartIndex, renderEndIndex }`)

> Returns the vertical render range of the table

The vertical render range is the range of rows that are currently rendered in the table viewport.

### onReady (`({ api, dataSourceApi }) => void`)

> Called when the table has been layed out and sized and is ready to be used.

This callback prop will be called with an object containing the `api` (which is an instance of `InfiniteTableApi`) and [`dataSourceApi`](https://infinite-table.com/docs/reference/datasource-api/index.md) objects.

### startEdit (`({ rowIndex, columnId }) => Promise<boolean>`)

> Tries to start editing the cell specified by the given row index and column id.

Returns a promise that resolves to `true` if editing was started, or `false` if editing was not started because the cell is not editable.

See [`columns.defaultEditable`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns.defaultEditable) for more details on how to configure a cell as editable.

**Example: Starting an Edit via the API**

```ts
import {
  InfiniteTable,
  DataSource,
  InfiniteTablePropColumns,
  InfiniteTableApi,
} from '@infinite-table/infinite-react';
import { useCallback, useRef, useState } from 'react';

type Developer = {
  id: number;
  firstName: string;
  currency: string;
  stack: string;
  hobby: string;
  salary: string;
};
const dataSource: Developer[] = [
  {
    id: 1,
    firstName: 'John',
    currency: 'USD',
    stack: 'frontend',
    hobby: 'gaming',
    salary: 'USD 1000',
  },
  {
    id: 2,
    firstName: 'Jane',
    currency: 'EUR',
    stack: 'backend',
    hobby: 'reading',
    salary: 'EUR 2000',
  },
  {
    id: 3,
    firstName: 'Jack',
    currency: 'GBP',
    stack: 'frontend',
    hobby: 'gaming',
    salary: 'GBP 3000',
  },
  {
    id: 4,
    firstName: 'Jill',
    currency: 'USD',
    stack: 'backend',
    hobby: 'reading',
    salary: 'USD 4000',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id', defaultWidth: 80, defaultEditable: false },

  salary: {
    defaultWidth: 320,
    field: 'salary',
    header: 'Salary - edit accepts numbers only',
    style: { color: 'tomato' },
    getValueToEdit: ({ value }) => {
      return parseInt(value.substr(4), 10);
    },
    getValueToPersist: ({ value, data }) => {
      return `${data!.currency} ${parseInt(value, 10)}`;
    },
    shouldAcceptEdit: ({ value }) => {
      return parseInt(value, 10) == value;
    },
  },

  firstName: {
    field: 'firstName',
    header: 'Name',
  },
  currency: {
    field: 'currency',
    header: 'Currency',
  },
};

export default function InlineEditingExample() {
  const [activeRowIndex, setActiveRowIndex] = useState<number>(2);

  const apiRef = useRef<InfiniteTableApi<Developer> | null>(null);
  const onReady = useCallback(
    ({ api }: { api: InfiniteTableApi<Developer> }) => {
      apiRef.current = api;
    },
    [],
  );
  return (
    <>
      <button
        style={{
          border: '1px solid magenta',
          margin: 2,
          padding: 10,
          background: 'var(--infinite-background)',
          color: 'var(--infinite-cell-color)',
        }}
        onClick={() => {
          apiRef.current!.startEdit({
            rowIndex: activeRowIndex,
            columnId: 'salary',
          });
        }}
      >
        Edit the salary column for active row
      </button>

      <DataSource<Developer> primaryKey="id" data={dataSource}>
        <InfiniteTable<Developer>
          debugId="api-start-edit-example"
          onReady={onReady}
          columns={columns}
          columnDefaultEditable
          activeRowIndex={activeRowIndex}
          onActiveRowIndexChange={setActiveRowIndex}
        />
      </DataSource>
    </>
  );
}
```

### scrollCellIntoView (`(rowIndex: number; colIdOrIndex: string | number) => boolean`)

> Can be used to scroll a cell into the visible viewport

If scrolling was successful and the row and column combination was found, it returns `true`, otherwise `false`. The first arg of the function is the row index, while the second one is the column id or the column index (note this is not the index in all columns, but rather the index in current visible columns).

### scrollColumnIntoView (`(colId: string) => boolean`)

> Can be used to scroll a column into the visible viewport

If scrolling was successful and the column was found, it returns `true`, otherwise `false`.
The only parameter of this method is the column id.

### scrollLeft (`getter<number>|setter<number>`)

> Gets or sets the `scrollLeft` value in the grid viewport

Can be used as either a setter, to set the scroll left position or a getter to read the scroll left position.

```ts
// use as setter - will scroll the table viewport
api.scrollLeft = 200;

// use as getter to read the current scroll left value
const scrollLeft = api.scrollLeft;
```

### scrollRowIntoView (`(rowIndex: number) => boolean`)

> Can be used to scroll a row into the visible viewport

If scrolling was successful and the row was found, it returns `true`, otherwise `false`

### scrollTop (`getter<number>|setter<number>`)

> Gets or sets the `scrollTop` value in the grid viewport

Can be used as either a setter, to set the scroll top position or a getter to read the scroll top position.

```ts
// use as setter - will scroll the table viewport
api.scrollTop = 1200;

// use as getter to read the current scroll top value
const scrollTop = api.scrollTop;
```

### rowSelectionApi (`InfiniteTableRowSelectionApi`)

> Getter for the [Row Selection API](https://infinite-table.com/docs/reference/row-selection-api/index.md)

### rowDetailApi (`InfiniteTableRowDetailApi`)

> Getter for the [Row Detail API](https://infinite-table.com/docs/reference/row-detail-api/index.md)

### cellSelectionApi (`InfiniteTableCellSelectionApi`)

> Getter for the [Cell Selection API](https://infinite-table.com/docs/reference/cell-selection-api/index.md)

### setColumnFilter (`(columnId: string, value: any) =>void`)

> Sets a filter value for the specified column

### setColumnOrder (`(columnIds: string[] | true) => void`)

> Set the column order.

If `true` is specified, it resets the column order to the order the columns are specified in the [`columns`](https://infinite-table.com/docs/reference/infinite-table-props.md#columns) prop (the iteration order of that object).

```ts
api.setColumnOrder(['id', 'firstName', 'age']);
// restore default order
api.setColumnOrder(true);
```

### toggleGroupRow (`(groupKeys: any[]) => void`)

> Toggles the collapse/expand state of the specified group row

```tsx
api.toggleGroupRow(['USA', 'New York']); // toggle the group with these keys
```
