Skip to content

Use with React ​

The <Grid> component creates the grid, passes options in, turns core events into on<Name> props, and cleans up when it unmounts. Sorting, selection, editing and saving all run in core. This guide covers only what is specific to React. The parts shared by all three frameworks are in the Framework guide.

The example at the end of each section runs on the real @maxgrid/react. Each is one .tsx file you can copy as it is. The full list is in the React integration examples.

Install ​

react and react-dom are peer dependencies, and versions 18 and 19 are accepted. The wrapper tests run on React 19.

bash
pnpm add @maxgrid/react @maxgrid/themes
ts
// main.tsx: load the theme CSS once, at the app entry.
import '@maxgrid/themes/grid.css';

The grid fills the height of its parent. A parent without a height is 0 pixels tall, so nothing shows.

tsx
import { Grid, type GridOptions } from '@maxgrid/react';

interface Employee {
  id: number;
  name: string;
  department: string;
}

const options: GridOptions<Employee> = {
  columns: [
    { id: 'name', title: 'Name' },
    { id: 'department', title: 'Department' },
  ],
  rows: [
    { id: 1, name: 'Liam Carter', department: 'Engineering' },
    { id: 2, name: 'Emma Wilson', department: 'Design' },
  ],
  rowKey: 'id',
};

export function EmployeeGrid() {
  return (
    <div style={{ height: 300 }}>
      <Grid<Employee> options={options} />
    </div>
  );
}

What Grid accepts ​

KindNameDescription
propsoptionsGridOptions<TRow>. Required.
propsclassName, styleApplied to the <div> that holds the grid. A CSS class can set the height
propson<Name>One per core event (onSortChanged, onRowClicked …). See the events section
propsonComponentErrorReceives an exception that a cell component threw while rendering
refGridApi<TRow>null until the grid exists
hooksuseGridApi(), useGridChanges(api)Keep the ref value in state, and follow the change counters
funcsreactCell(Component), reactEditor(Component)Go into a column’s cellRenderer and cellEditor

There are no selectedKeys, sortModel or filterModel props. See Sync selection, sort and filter for why, and what to do instead.

Options reach the grid only when the reference changes ​

<Grid> calls core’s setOptions only when the options object has a new reference. A parent re-render alone does nothing. Two habits follow from that.

  • Keep the parts that never change outside the component. The column array is the usual one.
  • Build a new object with useMemo for the parts that change. Editing the object in place (options.rows.push(...)) keeps the same reference, so the grid does not notice.
tsx
const columns = [
  { id: 'name', title: 'Name' },
  { id: 'department', title: 'Department' },
];

export function EmployeeGrid({ rows }: { rows: Employee[] }) {
  const options = useMemo<GridOptions<Employee>>(() => ({ columns, rows, rowKey: 'id' }), [rows]);
  return (
    <div style={{ height: 300 }}>
      <Grid<Employee> options={options} />
    </div>
  );
}

Writing options= inline still renders correctly. The only cost is that setOptions runs on every parent render, and core compares the values and skips what did not change.

With tens of thousands of rows, build the rows once with useMemo. When only a few rows change, pass just those rows to api.updateRows instead of building new options.

Example: Handle 100,000 rows

Fetch from a server ​

Turn on the loading option while the request runs, then build new options with the new rows. To stop a slow, old response from overwriting a newer one, number each request and bump the number on unmount so a late answer is dropped. The same rule keeps the effect safe when Strict Mode runs it twice.

tsx
const latest = useRef(0);

const load = useCallback(() => {
  const ticket = ++latest.current;
  setLoading(true);
  fetchRows().then((next) => {
    if (ticket !== latest.current) return;
    setRows(next);
    setLoading(false);
  });
}, []);

useEffect(() => {
  load();
  return () => {
    latest.current += 1;
  };
}, [load]);

Example: Show loading while fetching from a server

Use TanStack Query ​

When a query library owns the data, the grid only receives data as rows. Cached data shows at once, and the rows stay while a refetch runs.

tsx
import { useQuery } from '@tanstack/react-query';

export function OrderGrid() {
  const { data, isFetching } = useQuery({ queryKey: ['orders'], queryFn: fetchOrders });

  const options = useMemo<GridOptions<Order>>(
    () => ({ columns, rows: data ?? [], rowKey: 'id', loading: isFetching && !data }),
    [data, isFetching],
  );
  return (
    <div style={{ height: 300 }}>
      <Grid<Order> options={options} />
    </div>
  );
}

Binding loading straight to isFetching flashes the indicator on every refetch. Turning it on only when there is no cached data shows it once. A cell component can read the query client with useQueryClient() too. See Read Context in cells.

Example: Connect a query cache to the grid

Handle events ​

Each prop is the core event name with on in front and a capital first letter (sortChanged becomes onSortChanged). Names and payloads match the table in Events.

tsx
<Grid<Employee>
  options={options}
  onRowClicked={({ row }) => setDraft({ ...row })}
  onSelectionChanged={({ selectedKeys }) => setCount(selectedKeys.length)}
/>
  • Only events that have a handler are subscribed. Without onScrolled, scrolling costs React nothing.
  • Changing a handler does not resubscribe. The latest function is always the one called, so an inline arrow function never reads stale state.
  • Removing a handler unsubscribes it.

Use GridApi ​

Receive it through ref. It is null before the grid exists and after it is gone. Pick how to receive it by asking whether the screen has to react to the api appearing.

SituationUse
A button must enable once api exists, or an effect needs ituseGridApi()
Only event handlers such as clicks use ituseRef<GridApi<Row> | null>(null)
tsx
import { Grid, useGridApi } from '@maxgrid/react';

export function Toolbar({ options }: { options: GridOptions<Employee> }) {
  const [api, gridRef] = useGridApi<Employee>();

  return (
    <>
      <button disabled={!api} onClick={() => api?.clearSelection()}>
        Clear selection
      </button>
      <div style={{ height: 300 }}>
        <Grid<Employee> ref={gridRef} options={options} />
      </div>
    </>
  );
}

useGridApi() returns [api, ref]. When the grid is created it renders once more, so disabled={!api} and similar code get the value. Use it too when a useEffect(() => ..., [api]) in the same component subscribes or sets initial state.

Work that must run exactly once after creation can go in onReady={({ api }) => ...}.

Example: Call GridApi directly through a ref

Sync selection, sort and filter ​

The React wrapper supports uncontrolled use only. The grid owns selection, sort and filter, and React state is a copy.

  • Read: receive onSelectionChanged, onSortChanged and onFilterChanged, and keep the value in useState.
  • Write: call api.setSelectedKeys, api.setSortModel or api.setFilterModel. The new value comes back through the same event.
  • Initial value: set it in onReady={({ api }) => api.setSortModel([...])}.

There are two reasons for not pushing values back through props. setSelectedKeys throws for a key that does not exist, and handling that exception during React’s render would make the wrapper own business logic. And the wrapper would have to break the loop event → state → props → event. The rules that make sort, filter and selection affect one another also stay consistent when they live in one place, core.

tsx
const [api, gridRef] = useGridApi<Employee>();
const [selected, setSelected] = useState<RowKey[]>([]);

<button onClick={() => api?.setSelectedKeys([1, 2, 3])}>Select first 3</button>
<Grid<Employee>
  ref={gridRef}
  options={options}
  onSelectionChanged={({ selectedKeys }) => setSelected(selectedKeys)}
/>

Example: Keep selection and sort in step with React state

Sync with the URL query ​

The rule is the same when the URL is the source of truth. When the URL changes, call api.setFilterModel and api.setSortModel in a useEffect. Write what the grid changes back to the URL from the events. Writing the same value again does nothing, so there is no loop.

tsx
const [searchParams, setSearchParams] = useSearchParams(); // React Router
const department = searchParams.get('dept') ?? '';

useEffect(() => {
  api?.setFilterModel(department ? { match: 'all', items: [/* … */] } : null);
}, [api, department]);

<Grid<Employee>
  ref={gridRef}
  options={options}
  onFilterChanged={({ filterModel }) => {
    /* read the department from the filter model and write it with setSearchParams */
  }}
/>;

The example swaps the router for a tiny hook so it runs on its own. Two lines of that hook change to useSearchParams. When two events arrive in one tick, use the updater form (setState((current) => …)) so the second does not overwrite the first.

Example: Sync filter and sort with the URL query

Edit a row in a form ​

Writing form input straight into the row object changes the grid’s original data on every keystroke and skips change tracking. Copy the row when it is clicked, use the copy as form state, and call api.updateRows on apply to replace the row with the same key.

tsx
<Grid<Employee> ref={gridRef} options={options} onRowClicked={({ row }) => setDraft({ ...row })} />;

function apply() {
  if (draft) api?.updateRows([draft]);
}

Example: Edit a clicked row in a form and apply it

Draw cells with React components ​

Put reactCell(Component) in a column’s cellRenderer and reactEditor(Component) in cellEditor. The component renders into the cell through createPortal, so events, focus and accessibility attributes behave like any React component. The full description is in Cells from components. This section covers what trips people up in React.

tsx
import { Grid, reactCell, type CellRenderProps } from '@maxgrid/react';

function StatusBadge({ value }: CellRenderProps<Employee>) {
  return <span className={value ? 'badge-on' : 'badge-off'}>{value ? 'Active' : 'On leave'}</span>;
}

const columns = [
  { id: 'name', title: 'Name' },
  { id: 'active', title: 'Status', cellRenderer: reactCell(StatusBadge) },
];

A renderer receives value, row, rowKey, rowIndex, columnId, text and kind.

Create components once ​

reactCell(Component) builds one cell factory per component and remembers it. As long as you pass the same component, changing options does not rebuild the cells. If a render creates a new component function (calling reactCell(() => <b />) inside the render), every cell is rebuilt each time.

  • If the component needs nothing from its parent, define it at the top level of the module.
  • If it has to call a parent callback, build the options once with useMemo(() => ({ columns: [...] }), []), or pass the callback down through Context.

Example: Draw a status badge and a button as cell components

Read Context in cells ​

Cell components render at the <Grid> position in the React tree. Values from Providers above <Grid> (useContext, theme, i18n, query client) are visible as they are, with no need to wrap them in a Provider again. When a Context value changes, the visible cell components render again. If a cell needs the parent’s api or a callback, passing it through Context is the simplest way.

Example: Read a Context value inside a cell component

Components are reused while scrolling ​

There are only as many components as visible rows, and scrolling gives the same component the props of another row. A value held with useState inside the component stays when the row changes. To tie state to a row, render an inner component from the outside with rowKey as its key. With 100,000 rows, the number of components still stays at the number of visible rows.

tsx
function Notes(props: CellRenderProps<Employee>) {
  return <NotesInner key={props.rowKey} {...props} />;
}

Cell editors ​

An editor component reports a value with onChange(value), ends the edit with commit() and cancels with cancel(). The grid handles Enter, Esc and Tab, so the component does not. An editor that finishes the moment you pick something, such as a select, calls commit() after onChange.

tsx
function DepartmentEditor({ value, error, onChange, commit }: CellEditorProps<Employee>) {
  return (
    <select
      defaultValue={String(value ?? '')}
      aria-invalid={error !== null}
      onChange={(event) => {
        onChange(event.target.value);
        commit();
      }}
    >
      {DEPARTMENTS.map((d) => (
        <option key={d}>{d}</option>
      ))}
    </select>
  );
}

error is the validation message after a failed check, or null. Enter pressed while composing Hangul (IME) does not commit the edit. When the editor opens, the first input, select or textarea takes focus. Add data-mxg-autofocus to focus a specific element.

Example: Build a cell editor as a React component

A throwing component does not stop the grid ​

Each cell has its own error boundary. Only that cell turns into ⚠ 오류 (⚠ Error with locale: 'en'), and the rest stay as they were. The cell tries again the next time it receives new props. The exception reaches onComponentError, or console.error when you do not set one.

tsx
<Grid<Employee> options={options} onComponentError={(error) => report(error)} />

Build a save button ​

saveMode: 'batch' and saveHandler belong to core (Save changes in a batch). In React, useGridChanges(api) returns the change counters and the saving flag as state.

tsx
const [api, gridRef] = useGridApi<Employee>();
const { count, added, modified, removed, saving } = useGridChanges(api);

<button disabled={!count || saving} onClick={() => api?.save()}>
  {saving ? 'Saving…' : `Save (${count})`}
</button>
<button disabled={!count || saving} onClick={() => api?.rollbackChanges()}>Discard</button>
<Grid<Employee> ref={gridRef} options={options} />

The hook only subscribes to changesCountChanged and keeps the value in state. A row the server rejects stays as a change and shows its error in the cell.

Example: Build a save button for batched changes

Theme and density ​

The theme is the data-mxg-theme attribute on the grid or any ancestor. Put it on a wrapper element and only that grid changes. The options stay untouched, so the grid is not rebuilt. Density is the density option, so build new options only when it changes.

tsx
<div data-mxg-theme={dark ? 'dark' : 'light'} style={{ height: 300 }}>
  <Grid<Employee> options={options} />
</div>

To switch the whole page, set the attribute on document.documentElement. The CSS variables you can use are in Theme.

Example: Switch the theme and density

Strict Mode ​

In development, Strict Mode runs effects as mount, cleanup, mount. <Grid> creates the grid in a layout effect and calls destroy() in the cleanup, so one grid is left when the second mount finishes. The first grid is cleaned up before its onReady arrives, so even in development onReady fires once, for the grid that stays.

If onReady or a useEffect of yours creates a subscription or a timer, return a cleanup function so Strict Mode does not stack two. An effect that waits for a server response can use the request-number approach above.

Example: One grid is left under Strict Mode

Next.js and server rendering ​

On the server, the grid is not created and only an empty <div> is rendered. The grid appears after the client mounts, so the server HTML and the client HTML have the same structure and hydration does not mismatch. Importing the package does not touch window or document. The package bundle starts with 'use client', so importing Grid from a Server Component raises no error.

However, options.columns holds functions such as reactCell. Functions cannot cross from the server to the client, so the file that builds options must be a Client Component.

tsx
// app/employees/employee-grid.tsx
'use client';

import { Grid, type GridOptions } from '@maxgrid/react';

export function EmployeeGrid({ rows }: { rows: Employee[] }) {
  const options = useMemo<GridOptions<Employee>>(() => ({ columns, rows, rowKey: 'id' }), [rows]);
  return (
    <div style={{ height: 400 }}>
      <Grid<Employee> options={options} />
    </div>
  );
}
tsx
// app/employees/page.tsx: the Server Component loads the data and passes it down.
import { EmployeeGrid } from './employee-grid';

export default async function Page() {
  const rows = await loadEmployees();
  return <EmployeeGrid rows={rows} />;
}

The props a Server Component passes to a Client Component must be serializable. rows can cross, but columns that contain reactCell(...) cannot, so define the columns in the client file.

  • To keep a placeholder in the server HTML. Render an element of the same height first and swap it after mount. The layout does not shift.
  • When the code that builds options reads window or localStorage. Load that component with next/dynamic and { ssr: false }. That option works only inside a Client Component.
  • Pages Router. The same rules apply. 'use client' is not needed, and code that reads window goes behind next/dynamic with ssr: false.

Load the theme CSS once in the root layout (app/layout.tsx).

What was checked (2026-11-28)

Next.js 16.4.6 (App Router, Turbopack), React 19.3.1 and the published @maxgrid/react 1.7.2, with next build and next start, checked in Chromium (next dev was checked with 1.7.0).

  • The server HTML holds only an empty container, and the grid is drawn on the client with no hydration warning. After 2,000-row virtual scrolling, route changes away and back, and dev-mode StrictMode and HMR, one grid remains.
  • A server component can import Grid. Passing options that hold a function (such as cell) from a server component stops the build with Functions cannot be passed directly to Client Components.
  • createGantt and attachGrid from @maxgrid/gantt and downloadXlsx from @maxgrid/export work in a client component's effect and click handler.
  • Opened on a non-localhost host without a license key, the evaluation strip appears under the grid and the chart, an evaluation-mode notice appears in the console, and server rendering finishes without errors. Pass the key as licenseKey: process.env.NEXT_PUBLIC_MXG_KEY; NEXT_PUBLIC_ values are inlined at build time, so set it before next build. A valid key was not tried (a wrong key gives a malformed-key notice).
  • CSP: with a middleware (proxy.ts) that makes a nonce, script-src 'nonce-…' 'strict-dynamic' and style-src 'self' 'nonce-…' work for the grid and the Gantt chart. The grid uses inline style attributes, so style-src-attr 'unsafe-inline' is needed too.

In 1.7.0 <Grid> did not fill the height of its parent <div>, so it overflowed a parent shorter than the default height (400px). From 1.7.1 the parent-height examples on this page work as written. In 1.7.0, also pass <Grid style={{ height: '100%' }} />.

TypeScript generics ​

Pass the row type to <Grid>, the options and the ref.

WhereType
Component<Grid<Employee> options={...} />
OptionsGridOptions<Employee>
RefGridApi<Employee>, useGridApi<Employee>()
row in an event payloadEmployee (follows from the type you gave the component)
Props of a cell componentCellRenderProps<Employee>, CellEditorProps<Employee>
Save handlerSaveHandler<Employee>

<Grid> is a generic component. Write <Grid<Employee> …> and row in an event handler is an Employee. Without it, the type is inferred from options.

A reusable component that wraps the grid passes the row type through.

tsx
import { Grid, type GridEventProps, type GridOptions } from '@maxgrid/react';

interface DataGridProps<TRow extends object> extends GridEventProps<TRow> {
  options: GridOptions<TRow>;
  height?: number;
}

export function DataGrid<TRow extends object>({
  options,
  height = 400,
  ...events
}: DataGridProps<TRow>) {
  return (
    <div style={{ height }}>
      <Grid<TRow> options={options} {...events} />
    </div>
  );
}

@maxgrid/react also re-exports core types such as GridOptions, ColumnDef and GridApi. You do not need to install @maxgrid/core separately.

Common mistakes ​

  • Adding rows with options.rows.push(...). The reference is the same, so the grid does not notice. Build new options from a new array, or use api.addRows.
  • Calling reactCell(() => ...) inside a render. Each render creates a new component type and every cell is rebuilt. Define the component at module level, or build it once with useMemo.
  • Writing form input into the row object. The grid’s original data changes on each keystroke and change tracking is skipped. Edit a copy and call api.updateRows on apply.
  • Reading ref.current right after mount. It is null before the grid exists. Receive it with useGridApi, or wait for onReady.
  • Passing a reactCell to api.setColumns(). Component cells are connected as <Grid options> passes them through. Passing them to setColumns directly leaves them unconnected, and the cell shows an error. To change columns, build new options.
  • Passing ref.current to useGridChanges. It can be null during render, so no subscription is made. Pass the api that useGridApi() returns.
  • A parent without a height. The grid is invisible. Give the height in CSS.
  • useState inside a cell component leaking to the next row. Slots are reused. Use rowKey as a key from the outside.
  • Using reactCell in a Server Component file. Functions cannot cross to the client and the build fails. Build options in a 'use client' file.

Example index ​

What you want to doExample
Sync selection and sortState and grid in sync
Fetch from a serverShow loading
Connect a query cacheQuery cache
Edit in a formRow to form
Draw cells with componentsBadge and button cells
Edit cells with componentsComponent editor
Use ContextContext in cells
Sync with the URL queryQuery sync
Large data100,000 rows
Save buttonChange state
Switch the themeTheme and density
Strict ModeOne grid is left
Call GridApiDirect call through a ref