Movatterモバイル変換


[0]ホーム

URL:


<DatagridAG>

ThisEnterprise Edition component is an alternative datagrid component with advanced features, based onag-grid.

Here is a (non-exhaustive) list offeatures that<DatagridAG> offers:

  • In place editing of cells or rows
  • Columns resizing and reordering
  • Row and column pinning
  • Advanced filtering
  • DOM Virtualization
  • Row selection and bulk actions
  • Row animation
  • Draggable rows
  • Multi-column sorting
  • Keyboard navigation
  • Themes
  • Automatic page size
  • Automatic column size
  • Compatibility with React Admin fields

Additionally,<DatagridAG> is compatible with theEnterprise version of ag-grid, which offers even more features:

  • Row Grouping
  • Range selection
  • Aggregation
  • Tree Data
  • Pivoting
  • Master Detail views
  • Range Selection
  • Excel Export
  • Status bar
  • Context menu
  • More advanced filtering
  • And more…

You can test it live inthe Enterprise Edition Storybook.

Installation

npminstall--save @react-admin/ra-datagrid-ag# oryarn add @react-admin/ra-datagrid-ag

Tip:ra-datagrid-ag is part of theReact-Admin Enterprise Edition, and hosted in a private npm registry. You need to subscribe to one of the Enterprise Edition plans to access this package.

Data Fetching

This package proposes 2 components, each with its own data fetching strategy:

  • <DatagridAG> works just like<Datagrid>, displaying the data fetched by its parent component (usually a<List>) and calling the API each time the user changes the sorting, filtering, or pagination. However it is not compatible with some of the features provided byag-grid (seelimitations).
  • <DatagridAGClient> fetches all the data from the API at once, and then performs filtering, sorting and paginationclient-side. This allows for a more responsive UI and enables some client-side only features, but only works for limited datasets (around a few thousand records). The client-side performance isn’t affected by a large number of records, as ag-grid usesDOM virtualization.

<DatagridAG> doesn’t currently support ag-grid’sserver-side row model.

<DatagridAG>

<DatagridAG> is an alternative datagrid component with advanced features, based onag-grid.

DatagridAG PostList

Usage

Use<DatagridAG> as a child of a react-admin<List>,<ReferenceManyField>, or any other component that creates aListContext.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

Here are the important things to note:

  • You need to import the ag-grid stylesheetsag-grid.css andag-theme-alpine.css.
  • The columns are defined using thecolumnDefs prop. Seethe dedicated doc section for more information.

Usage Inside An<InfiniteList>

<DatagridAG> also supports being used as a child of a react-admin<InfiniteList>.

It only requires setting thepagination prop tofalse, because<DatagridAG> will itself detect when it needs to fetch more data, and the<InfiniteList> default pagination component would conflict with this behavior.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{InfiniteList}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<InfiniteListpagination={false}><DatagridAGcolumnDefs={columnDefs}/></InfiniteList>);};

Filter Syntax

<DatagridAG> displays the data fetched by its parent (usually<List>).

<DatagridAG> provides advanced filtering controls and uses a special syntax to support operators (“contains”, “equals”, “not equals”, etc.). This syntax isn’t supported bydataProvider.getList() by default, so<DatagridAG> converts the internal filter representation into key-value pairs, using the familiar filter syntax:

// ag-grid internal filter format{athlete:{filterType:'text',type:'equals',filter:'mich',},age:{filterType:'number',type:'lessThan',filter:30,},gold_medals:{filterType:'number',type:'inRange',filter:5,filterTo:10,},country:{filterType:'text',type:'blank',},}// is turned into react-admin filter format by default{athlete_eq:'mich',age_lt:30,gold_medals_gte:5,gold_medals_lte:10,country_eq:null,}

This conversion is done via to thegetRaFilters andgetAgGridFilters callbacks, that you can override to customize the format of the filter param sent to the dataProvider.

ag-grid provides default filters fortext,number, anddate columns. Some filters may not be supported by your backend, likestartsWith orendsWith. You can remove these unsupported filters using thedefaultColDef and thecolumnDefs props.

import{List}from'react-admin';import{DatagridAG}from'@react-admin/datagrid-ag';constOlympicWinnersList=()=>{conststringFilterParams={filterParams:{// allow only some filter types for string columnsfilterOptions:['contains','equals','notEqual','blank'],},};constcolumnDefs=[{field:'athlete',...stringFilterParams},{field:'age'},{field:'country',...stringFilterParams},{field:'year'},];constdefaultColDef={filterParams:{maxNumConditions:1,// limit the number of conditions to 1filterOptions:[// list supported filter types by default'equals','notEqual','greaterThan','greaterThanOrEqual','lessThan','lessThanOrEqual','contains','inRange','blank',],},};return(<List><DatagridAGcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

Limitations

<DatagridAG> is designed to work with partial datasets and load data upon request, thanks to theListContext. It allows to work with a larger dataset, as it uses the dataProvider to fetch paginated data. However, this means that it can’t use some of the features offered byag-grid such as:

  • Row grouping
  • Pivoting
  • Aggregation
  • Advanced filtering (and having multiple filters)
  • Multi-column sorting
  • Automatic page size

If you need to use these features, you can use the<DatagridAGClient> component instead of<DatagridAG>.

Props

PropRequiredTypeDefaultDescription
bulkActionButtonsOptionalElement<BulkDelete Button>The component used to render the bulk action buttons
cellEditorOptionalString, Function or Element Allows to use a custom component to render the cell editor
cellRendererOptionalString, Function or Element Allows to use a custom component to render the cell content
columnDefsRequiredArrayn/aThe columns definitions
darkThemeOptionalString'ag-theme-alpine-dark'The name of the ag-grid dark theme
defaultColDefOptionalObject The default column definition (applied to all columns)
getAgGridFiltersOptionalFunction A function mapping react-admin filters to ag-grid filters
getRaFiltersOptionalFunction A function mapping ag-grid filters to react-admin filters
mutationOptionsOptionalObject The mutation options
preferenceKeyOptionalString orfalse${resource}.ag-grid.paramsThe key used to persistgridState in the Store.false disables persistence.
sxOptionalObject The sx prop passed down to the wrapping<div> element
themeOptionalString'ag-theme-alpine'The name of the ag-grid theme

<DatagridAG> also accepts the same props as<AgGridReact> with the exception ofrowData, since the data is fetched from the List context.

bulkActionButtons

You can use thebulkActionButtons prop to customize the bulk action buttons, displayed when at least one row is selected. Don’t forget to add an initial column in thecolumnDefs to allow row selection.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,BulkExportButton,BulkDeleteButton}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';// Define the custom bulk action buttonsconstPostBulkActionButtons=()=>(<><BulkExportButton/><BulkDeleteButton/></>);exportconstPostList=()=>{constcolumnDefs=[// Add a column for row selection{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}// Pass the custom bulk action buttonsbulkActionButtons={<PostBulkActionButtons/>}/></List>);};

cellEditor

In a column definition, you can use thecellEditor field to specify a custom cell editor. You can use anyEdit Component supported byag-grid, includingCustom Components.

In addition to that,<DatagridAG> supports usingReact Admin inputs ascellEditor, such as<TextInput> or even<ReferenceInput>.

This allows to leverage all the power of react-admin inputs in your grid, for example to edit a reference.

To use a React Admin input ascellEditor, you need to pass it as aReact Element:

import{List,ReferenceInput}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"/>),},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

If you are passing a React Admin input asReact Element, there are two additional props you can use:submitOnChange andnoThemeOverride.

These props need to be passed ascellEditorParams.

submitOnChange allows to submit the change to ag-grid as soon as the input value changes, without waiting for the user to submit the form (e.g. by pressing Enter or clicking outside the cell).

This provides a better UX for example with components such as<AutocompleteInput> or<SelectInput>, as the value is immediately updated after the user selects an option.

import{List,ReferenceInput}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"/>),cellEditorParams:{submitOnChange:true,},},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

noThemeOverride allows to preventDatagridAG from applying custom styles to the input.

Indeed,DatagridAG applies custom styles to the inputs to make them look like ag-grid cells. However, this can cause issues for instance when rendering aDialog containing additional inputs inside the cell editor. This can happen, for example, if you are using a custom create component with<AutocompleteInput create>.

To solve this issue, you can setnoThemeOverride totrue and apply your own styles to the input component.

import{styled}from'@mui/material';import{List,ReferenceInput,AutocompleteInput}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';import{CreatePostDialog}from'./CreatePostDialog';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"><AutocompleteInputWithCreate/></ReferenceInput>),cellEditorParams:{noThemeOverride:true,},},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};constAutocompleteInputWithCreate=()=>{return(<StyledAutocompleteInputvariant="outlined"ListboxComponent={StyledListbox}create={<CreatePostDialog/>}/>);};constStyledAutocompleteInput=styled(AutocompleteInput)({'& .MuiTextField-root':{margin:'1px 0px',},'& .MuiTextField-root fieldset':{border:'none',},'& .MuiTextField-root input':{fontSize:14,},'& .MuiInputLabel-root':{display:'none',},});constStyledListbox=styled('ul')({fontSize:14,});

Tip: Be sure to read theFine Tuning Input Components Used As Cell Editor section to improve the UX of your custom cell editors.

Tip: Using a customcellEditor works great in combination with a customcellRenderer.

Note: React Admin inputs used adcellEditor do not (yet) support form validation.

cellRenderer

In a column definition, you can use thecellRenderer field to specify a custom cell renderer. In addition toag-grid’s cell rendering abilities,<DatagridAG> supportsreact-admin fields incellRenderer. This is particularly useful to render a<ReferenceField> for instance.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{EmailField,List,ReferenceField,TextField}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[{field:'id',editable:false,},{field:'author.name'},{field:'author.email',cellRenderer:<EmailFieldsource="author.email"/>,},{field:'post_id',headerName:'Post',cellRenderer:(<ReferenceFieldsource="post_id"reference="posts"/>),},{field:'created_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

DatagridAG RA Fields

Note: You still need to pass thesource prop to the field.

Tip: This works great in combination with a customcellEditor.

columnDefs

ThecolumnDefs prop is the most important prop of<DatagridAG>. It defines the columns of the grid, and their properties. It is an array of objects, each object representing a column.

Here is an example with a complete column definitions object:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';consttruncate=(str:string,n:number)=>{returnstr.length>n?str.slice(0,n-1)+'...':str;};exportconstPostList=()=>{constcolumnDefs=[{field:'id',editable:false,headerCheckboxSelection:true,checkboxSelection:true,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at',headerName:'Publication Date',},{field:'body',cellRenderer:({value})=>truncate(value,20),},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

DatagridAG custom columnDefs

Have a look atthe ag-grid documentation for the exhaustive list of column properties.

darkTheme

You can use a different dark theme for the grid by passing adarkTheme prop. It will be applied automatically whenever React Admin theme is set to dark.You can for instance use one of thethemes provided by ag-grid, likeag-theme-balham orag-theme-alpine-dark:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-balham.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}theme="ag-theme-balham"darkTheme="ag-theme-balham-dark"/></List>);};

DatagridAG Dark

Tip: Remember to import the corresponding stylesheet (e.g.ag-theme-balham[.min].css forag-theme-balham).

defaultColDef

ThedefaultColDef prop allows you to define default properties for all columns. It is an object with the same properties ascolumnDefs objects.

In the example below, the configuration enables flex mode on the columns, and sets each column to take 1/3 of the available space:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constdefaultColDef={flex:1,};return(<List><DatagridAGcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

DatagridAG defaultColDef

getAgGridFilters

You can use thegetAgGridFilters prop to provide a function that transforms the filters from the dataProvider to the ag-grid format.

The default implementation turns key/value filters into ag-grid filters. For instance, the following data provider filters:

{athlete_eq:'mich',age_lt:'30',country_q:'fr',}

Will be turned into:

{athlete:{filterType:'text',type:'equals',filter:'mich',},age:{filterType:'text',type:'lessThan',filter:'30',},country:{filterType:'text',type:'contains',filter:'fr',},}

Pass your owngetAgGridFilter function if your data provider uses another filter format, so that<DatagridAG> can display them correctly. Use the default implementation as a starting point:

import{List}from"react-admin";import{DatagridAG}from"@react-admin/ra-datagrid-ag";importtype{FilterModel}from"@ag-grid-community/core";constgetAgGridFilter=(raFilter:string,source:string):FilterModel=>{constfilterMapping={eq:"equals",neq:"notEqual",gt:"greaterThan",gte:"greaterThanOrEqual",lt:"lessThan",lte:"lessThanOrEqual",q:"contains",};consthasOperator=source.includes("_");constoperator=source.split("_").at(-1);constcolId=source.split("_").slice(0,-1).join("_");if(!hasOperator||!operator){return{[source]:{filterType:"text",type:"equals",filter:raFilter,},};}if(!filterMapping[operator]){console.warn(`Unsupported filter suffix:${operator}`);return{};}return{[colId]:{filterType:"text",type:filterMapping[operator],filter:raFilter,},};};constgetAgGridFilters=(raFilters:{[key:string]:string;}):FilterModel=>{returnObject.entries(raFilters).reduce((acc,[source,raFilter])=>{return{...acc,...getAgGridFilter(raFilter,source),};},{});};exportconstPostList=()=>{constcolumnDefs=[{field:"title"},{field:"published_at"},{field:"body"},];return(<List><DatagridAGcolumnDefs={columnDefs}getAgGridFilters={getAgGridFilters}/></List>);};

getRaFilters

You can use thegetRaFilters prop to provide a function that transforms the filters from the ag-grid format to the react-admin format.

The default implementation turns ag-grid filters into key/value pairs. For instance, the following ag-grid filters:

{athlete:{filterType:'text',type:'equals',filter:'mich',},age:{filterType:'number',type:'lessThan',filter:30,},gold_medals:{filterType:'number',type:'inRange',filter:5,filterTo:10,},country:{filterType:'text',type:'blank',},}

Will be turned into:

{athlete_eq:'mich',age_lt:30,gold_medals_gte:5,gold_medals_lte:10,country_eq:null,}

Pass your owngetRAFilter function if your data provider uses another filter format. Use the default implementation as a starting point:

import{List}from"react-admin";import{DatagridAG}from"@react-admin/ra-datagrid-ag";importtype{FilterModel}from"@ag-grid-community/core";constgetRAFilter=(agFilter:FilterModel,source:string):{[key:string]:string}=>{constfilterMapping={equals:"_eq",notEqual:"_neq",greaterThan:"_gt",greaterThanOrEqual:"_gte",lessThan:"_lt",lessThanOrEqual:"_lte",contains:"_q",inRange:()=>({[`${source}_gte`]:agFilter.filter,[`${source}_lte`]:agFilter.filterTo,}),blank:()=>({[`${source}_eq`]:null,}),};if(!filterMapping[agFilter.type]){console.warn(`Unsupported filter type:${agFilter.type}`);return{};}constfilter=filterMapping[agFilter.type];if(typeoffilter==="function"){returnfilter();}return{[`${source}${filter}`]:agFilter.filter,};};constgetRaFilters=(agGridFilters:FilterModel):{[key:string]:string}=>{returnObject.entries(agGridFilters).reduce((acc,[source,agFilter])=>{return{...acc,...getRAFilter(agFilter,source),};},{});};exportconstPostList=()=>{constcolumnDefs=[{field:"title"},{field:"published_at"},{field:"body"},];return(<List><DatagridAGcolumnDefs={columnDefs}getRaFilters={getRaFilters}/></List>);};

mutationOptions

You can use themutationOptions prop to provide options to thedataProvider.update() call triggered when a cell or a row is edited.

In particular, this allows to choose themutationMode, and/or to pass ameta object to the dataProvider.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}mutationOptions={{meta:{foo:'bar'},mutationMode:'optimistic',}}/></List>);};

This also allows to display a notification after the mutation succeeds.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,useNotify}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constnotify=useNotify();constonSuccess=React.useCallback(()=>{notify('ra.notification.updated',{type:'info',messageArgs:{smart_count:1,},undoable:true,});},[notify]);return(<List><DatagridAGcolumnDefs={columnDefs}mutationOptions={{mutationMode:'undoable',onSuccess,}}/></List>);};

preferenceKey

<DatagridAG> will store thegridState in theStore, under the key${resource}.ag-grid.params.grid. ThisgridState persisted in the store is applied once when the grid is created, it means that users will find the grid as they left it previously.

If you wish to change the key used to store the columns order and size, you can pass apreferenceKey prop to<DatagridAG>.

<List><DatagridAGcolumnDefs={columnDefs}preferenceKey="my-post-list"/></List>

If, instead, you want to disable the persistence of the columns order and size, you can passfalse to thepreferenceKey prop:

<List><DatagridAGcolumnDefs={columnDefs}preferenceKey={false}/></List>

Tip: If you update thecolumnDefs prop, and users already customized columns in a previous version of the app, the two versions will conflict. You can invite users to log out to reset the store, or add custom logic toinvalidate the react-admin Store.

sx

You can usethesx prop to customize the grid’s style:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}sx={{'& .ag-header-cell-comp-wrapper':{color:'red'}}}/></List>);};

DatagridAG sx

It can also be helpful to change the default grid’s height (calc(100vh - 96px - ${theme.spacing(1)})):

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[/* ... */];return(<List><DatagridAGcolumnDefs={columnDefs}sx={{height:'calc(100vh - 250px)'}}/></List>);};

DatagridAG sx height

theme

You can use a different theme for the grid by passing atheme prop. You can for instance use one of thethemes provided by ag-grid, likeag-theme-balham orag-theme-alpine-dark:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-balham.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}theme="ag-theme-balham"/></List>);};

DatagridAG Dark

Tip: Remember to import the corresponding stylesheet (e.g.ag-theme-balham[.min].css forag-theme-balham).

AgGrid Defaults

Under the hood,<DatagridAG> is a wrapper around<AgGridReact>. However it sets some important default values:

  • pagination is set tofalse as the<List> component handles it
  • paginationAutoPageSize is set tofalse
  • animateRows is set totrue
  • rowSelection is set to'multiple'
  • suppressRowClickSelection is set totrue
  • readOnlyEdit is set totrue
  • getRowId is set to use the recordid field

It also register the following defaultmodules:ClientSideRowModelModule,CommunityFeaturesModule andCsvExportModule. If you wish to add custom modules, make sure you have at least theClientSideRowModelModule:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';import{ClientSideRowModelModule}from'@ag-grid-community/client-side-row-model';import{CsvExportModule}from'@ag-grid-community/csv-export';import{ClipboardModule}from'@ag-grid-enterprise/clipboard';constmodules=[ClientSideRowModelModule,CsvExportModule,ClipboardModule];exportconstPostList=()=>{constcolumnDefs=[{field:'id',editable:false,headerCheckboxSelection:true,checkboxSelection:true,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at',headerName:'Publication Date',},];return(<List><DatagridAGcolumnDefs={columnDefs}modules={modules}/></List>);};

It also includes adefaultColDef object with the following properties:

{resizable:true,filter:true,sortable:true,editable:true,headerCheckboxSelectionFilteredOnly:true,headerCheckboxSelectionCurrentPageOnly:true,}

You may override any of these defaults by passing the corresponding props to<DatagridAG> (defaultColDef will be merged with the defaults).

Accessing The Grid API

You can access the grid’sapi by passing aref to<DatagridAG>.

In this example, we use theapi to automatically resize all columns to fit their content on first render:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{AgGridReact}from'ag-grid-react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);return(<List><DatagridAGcolumnDefs={columnDefs}ref={gridRef}onFirstDataRendered={onFirstDataRendered}/></List>);};

Check out theGrid API documentation to learn more.

Changing The Default Column Width

By default, ag-grid will render each column with a fixed size.

You can choose to enable flex mode by setting theflex prop either on thecolumnDefs or on thedefaultColDef:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at',flex:1},{field:'body'},];constdefaultColDef={flex:2,};return(<List><DatagridAGcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

DatagridAG flex

Alternatively, you can use the grid’sapi to callautoSizeAllColumns to automatically resize all columns to fit their content:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{AgGridReact}from'ag-grid-react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);return(<List><DatagridAGcolumnDefs={columnDefs}ref={gridRef}onFirstDataRendered={onFirstDataRendered}/></List>);};

DatagridAG auto size

Check out theColumn Sizing documentation for more information and more alternatives.

Selecting Rows And Enabling Bulk Actions

Just like<Datagrid>,<DatagridAG> supports row selection and bulk actions.

Add a column with the following definition to enable row selection:

{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},

Below is an example with thePostList component:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

DatagridAG selected rows

Just like with<Datagrid>, you can customize the bulk actions by passing abulkActionButtons prop to<DatagridAG>.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,BulkExportButton,BulkDeleteButton}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';constPostBulkActionButtons=()=>(<><BulkExportButton/><BulkDeleteButton/></>);exportconstPostList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}bulkActionButtons={<PostBulkActionButtons/>}/></List>);};

Enabling Full Row Edition

By default, editing is enabled on cells, which means you can edit a cell by double-clicking on it, and it will trigger a call to the dataProvider’supdate function.

DatagridAG edit cell

However, if you’d like to update the full row at once instead, you can enable full row editing by passingeditType="fullRow" to<DatagridAG>:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[/* ... */];return(<List><DatagridAGcolumnDefs={columnDefs}editType="fullRow"/></List>);};

DatagridAG edit row

Disabling Cell Edition

Seteditable: false in the definition of a column to disable the ability to edit its cells.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at',editable:false},{field:'body'},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

Alternatively, you can disable the ability to edit all cells by passingeditable: false to thedefaultColDef:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constdefaultColDef={editable:false,};return(<List><DatagridAGcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

Fine-Tuning Input Components Used As Cell Editor

ThecellEditor section already explains how you can use React Admin inputs as cell editor in ag-grid.

However, there are some tweaks you can apply to the input components to improve their UX when used as a cell editor.

Automatically Focus And Select The Input Value With<AutocompleteInput>

When rendering an<AutocompleteInput> as a cell editor, it can be useful to automatically focus and select the input value when the cell editor is opened. This saves time for the user, as they can start typing right away, or select an option from the list as it is already open.

This can be achieved using refs like so:

constAutocompleteInputWithAutoSelect=props=>{constinputRef=React.useRef<HTMLInputElement>(null);return(<AutocompleteInput{...props}TextFieldProps={{inputRef,ref:()=>{setTimeout(()=>{inputRef.current?.select();},50);},}}/>);};

Automatically Open The Options List With<SelectInput>

When rendering a<SelectInput> as a cell editor, it can be useful to automatically open the list of options when the cell editor is opened. This saves time for the user, as they can select an option from the list right away.

This can be achieved using thedefaultOpen prop like so:

constSelectInputWithDefaultOpen=props=>{return(<SelectInput{...props}SelectProps={{defaultOpen:true,}}/>);};

Allow To Create New Options On The Fly With<AutocompleteInput> Or<SelectInput>

As explained in thecellEditor section, a custom MUI theme will be applied to React Admin inputs to make them look like ag-grid cells. This theme can conflict with other input components that are rendered in the Dialog you open to create a new option on the fly.

This can be solved by passingnoThemeOverride: true to thecellEditorParams.

Besides, the submit button of the Dialog can conflict with the built-in cell editor event handler, resulting in the cell leaving the Edit mode before the newly created option could be selected.

This can be solved by stopping the event propagation when the submit button is clicked in the Dialog.

Here is a complete example of how to create a customAutocompleteInputWithCreate component that solves both issues:

importReactfrom'react';import{Button,Dialog,DialogActions,DialogContent,TextFieldasMUITextField,Stack,styled,}from'@mui/material';import{AutocompleteInput,List,ReferenceInput,useCreate,useCreateSuggestionContext,}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';constCreatePostDialog=()=>{const{filter,onCancel,onCreate}=useCreateSuggestionContext();const[title,setTitle]=React.useState(filter||'');const[create]=useCreate();consthandleSubmit=event=>{event.preventDefault();event.stopPropagation();// prevent the default handler from ag-gridcreate('posts',{data:{title},},{onSuccess:data=>{setTitle('');onCreate(data);},});};return(<DialogopenonClose={onCancel}><formonSubmit={handleSubmit}><DialogContent><Stackgap={4}><MUITextFieldname="title"value={title}onChange={event=>setTitle(event.target.value)}/></Stack></DialogContent><DialogActions><Buttontype="submit">Save</Button><ButtononClick={onCancel}>Cancel</Button></DialogActions></form></Dialog>);};constAutocompleteInputWithCreate=props=>{constinputRef=React.useRef<HTMLInputElement>(null);return(<StyledAutocompleteInput{...props}variant="outlined"ListboxComponent={StyledListbox}TextFieldProps={{inputRef,ref:()=>{setTimeout(()=>{inputRef.current?.select();},50);},}}create={<CreatePostDialog/>}/>);};constStyledAutocompleteInput=styled(AutocompleteInput)({'& .MuiTextField-root':{margin:'1px 0px',},'& .MuiTextField-root fieldset':{border:'none',},'& .MuiTextField-root input':{fontSize:14,},'& .MuiInputLabel-root':{display:'none',},});constStyledListbox=styled('ul')({fontSize:14,});exportconstCommentListWithAutocompleteWithCreate=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"><AutocompleteInputWithCreate/></ReferenceInput>),cellEditorParams:{submitOnChange:true,noThemeOverride:true,// prevent the default theme override},},];return(<List><DatagridAGcolumnDefs={columnDefs}/></List>);};

Using AG Grid Enterprise

<DatagridAG> is also compatible with theEnterprise version of ag-grid.

You can follow the instructions in theGetting Started with AG Grid Enterprise section of theGetting Started documentation to enable the Enterprise features.

Below is a short example of what you can achieve.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';import{AgGridReact}from'ag-grid-react';import'ag-grid-enterprise';importReactfrom'react';import{List}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';constOlympicWinnersList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'athlete'},{field:'age'},{field:'country'},{field:'year'},{field:'date'},{field:'sport'},{field:'gold'},{field:'silver'},{field:'bronze'},{field:'total'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);constdefaultColDef={enableRowGroup:true,};return(<List><DatagridAGcolumnDefs={columnDefs}defaultColDef={defaultColDef}ref={gridRef}onFirstDataRendered={onFirstDataRendered}rowGroupPanelShow="always"groupSelectsChildren/></List>);};

Adding An Expandable Panel (Master/Detail)

You can leverageag-grid Master Detail Module to add an expandable panel.

For instance, here’s how to show the comments of a post in an expandable panel:

DatagridAG Master Detail

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';import{AgGridReact}from'ag-grid-react';import{ColDef,CommunityFeaturesModule}from'@ag-grid-community/core';import{ClientSideRowModelModule}from'@ag-grid-community/client-side-row-model';import{CsvExportModule}from'@ag-grid-community/csv-export';import{MasterDetailModule}from'@ag-grid-enterprise/master-detail';importReactfrom'react';import{List,useDataProvider,useNotify}from'react-admin';import{DatagridAG}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constdataProvider=useDataProvider();constnotify=useNotify();constcolumnDefs:ColDef<any,any>[]=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title',flex:1,cellRenderer:'agGroupCellRenderer'},{field:'published_at'},];constdetailCellRendererParams={// provide the Grid Options to use on the Detail GriddetailGridOptions:{columnDefs:[{field:'body',flex:1},{field:'author.name'}],},// get the rows for each Detail GridgetDetailRowData:params=>{dataProvider.getManyReference('comments',{target:'post_id',id:params.data.id,pagination:{page:1,perPage:100},sort:{field:'created_at',order:'DESC'},filter:{},}).then(({data})=>{params.successCallback(data);}).catch(error=>{notify(error.message,{type:'error'});params.successCallback([]);});},};return(<Listresource="posts"><DatagridAGmasterDetailcolumnDefs={columnDefs}detailCellRendererParams={detailCellRendererParams}modules={[ClientSideRowModelModule,CommunityFeaturesModule,CsvExportModule,MasterDetailModule,]}/></List>);};

<DatagridAGClient>

<DatagridAGClient> is an alternative datagrid component with advanced features, based onag-grid. It is designed for small datasets that can be entirely loaded client-side (around a few thousand records). It supports infinite scrolling, grouping, multi-column sorting, and advanced filtering.

The client-side performance isn’t affected by a large number of records, as ag-grid usesDOM virtualization.

DatagridAGClient PostList

Usage

Use<DatagridAGClient> as a child of a react-admin<List>,<ReferenceManyField>, or any other component that creates aListContext.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

Here are the important things to note:

  • You need to import the ag-grid stylesheetsag-grid.css andag-theme-alpine.css.
  • To benefit from ag-grid’s filtering and sorting features (as well as some Enterprise features like grouping), you need to load the entire list of records client-side. To do so, you must set<List perPage> to a high number (e.g. 10,000).
  • As the pagination is handled by ag-grid, you can disable react-admin’s pagination with<List pagination={false}>.
  • The columns are defined using thecolumnDefs prop. Seethe dedicated doc section for more information.
  • <InfiniteList> is not supported.

The client-side performance isn’t affected by a large number of records, as ag-grid usesDOM virtualization.<DatagridAGClient> has been tested with 10,000 records without any performance issue.

Props

PropRequiredTypeDefaultDescription
bulkActionButtonsOptionalElement<BulkDelete Button>The component used to render the bulk action buttons
cellEditorOptionalString, Function or Element Allows to use a custom component to render the cell editor
cellRendererOptionalString, Function or Element Allows to use a custom component to render the cell content
columnDefsRequiredArrayn/aThe columns definitions
darkThemeOptionalString'ag-theme-alpine-dark'The name of the ag-grid dark theme
defaultColDefOptionalObject The default column definition (applied to all columns)
mutationOptionsOptionalObject The mutation options
paginationOptionalBooleantrueEnable or disable pagination
preferenceKeyOptionalString orfalse${resource}.ag-grid.paramsThe key used to persistgridState in the Store.false disables persistence.
sxOptionalObject The sx prop passed down to the wrapping<div> element
themeOptionalString'ag-theme-alpine'The name of the ag-grid theme

<DatagridAGClient> also accepts the same props as<AgGridReact> with the exception ofrowData, since the data is fetched from the List context.

bulkActionButtons

You can use thebulkActionButtons prop to customize the bulk action buttons, displayed when at least one row is selected.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,BulkExportButton,BulkDeleteButton}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';constPostBulkActionButtons=()=>(<><BulkExportButton/><BulkDeleteButton/></>);exportconstPostList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}bulkActionButtons={<PostBulkActionButtons/>}/></List>);};

cellEditor

In a column definition, you can use thecellEditor field to specify a custom cell editor. You can use anyEdit Component supported byag-grid, includingCustom Components.

In addition to that,<DatagridAGClient> supports usingReact Admin inputs ascellEditor, such as<TextInput> or even<ReferenceInput>.

This allows to leverage all the power of react-admin inputs in your grid, for example to edit a reference.

To use a React Admin input ascellEditor, you need to pass it as aReact Element:

import{List,ReferenceInput}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"/>),},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

If you are passing a React Admin input asReact Element, there are two additional props you can use:submitOnChange andnoThemeOverride.

These props need to be passed ascellEditorParams.

submitOnChange allows to submit the change to ag-grid as soon as the input value changes, without waiting for the user to submit the form (e.g. by pressing Enter or clicking outside the cell).

This provides a better UX for example with components such as<AutocompleteInput> or<SelectInput>, as the value is immediately updated after the user selects an option.

import{List,ReferenceInput}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"/>),cellEditorParams:{submitOnChange:true,},},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

noThemeOverride allows to preventDatagridAGClient from applying custom styles to the input.

Indeed,DatagridAGClient applies custom styles to the inputs to make them look like ag-grid cells. However, this can cause issues for instance when rendering aDialog containing additional inputs inside the cell editor. This can happen, for example, if you are using a custom create component with<AutocompleteInput create>.

To solve this issue, you can setnoThemeOverride totrue and apply your own styles to the input component.

import{styled}from'@mui/material';import{List,ReferenceInput,AutocompleteInput}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';import{CreatePostDialog}from'./CreatePostDialog';exportconstCommentList=()=>{constcolumnDefs=[// ...{field:'post_id',cellEditor:(<ReferenceInputsource="post_id"reference="posts"><AutocompleteInputWithCreate/></ReferenceInput>),cellEditorParams:{noThemeOverride:true,},},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};constAutocompleteInputWithCreate=()=>{return(<StyledAutocompleteInputvariant="outlined"ListboxComponent={StyledListbox}create={<CreatePostDialog/>}/>);};constStyledAutocompleteInput=styled(AutocompleteInput)({'& .MuiTextField-root':{margin:'1px 0px',},'& .MuiTextField-root fieldset':{border:'none',},'& .MuiTextField-root input':{fontSize:14,},'& .MuiInputLabel-root':{display:'none',},});constStyledListbox=styled('ul')({fontSize:14,});

Tip: Be sure to read theFine Tuning Input Components Used As Cell Editor section to improve the UX of your custom cell editors.

Tip: Using a customcellEditor works great in combination with a customcellRenderer.

Note: React Admin inputs used adcellEditor do not (yet) support form validation.

cellRenderer

In a column definition, you can use thecellRenderer field to specify a custom cell renderer. In addition toag-grid’s cell rendering abilities,<DatagridAGClient> supportsreact-admin fields incellRenderer. This is particularly useful to render a<ReferenceField> for instance.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{EmailField,List,ReferenceField,TextField}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstCommentList=()=>{constcolumnDefs=[{field:'id',editable:false,},{field:'author.name'},{field:'author.email',cellRenderer:<EmailFieldsource="author.email"/>,},{field:'post_id',headerName:'Post',cellRenderer:(<ReferenceFieldsource="post_id"reference="posts"/>),},{field:'created_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

DatagridAGClient RA Fields

Note: You still need to pass thesource prop to the field.

Tip: This works great in combination with a customcellEditor.

columnDefs

ThecolumnDefs prop is the most important prop of<DatagridAGClient>. It defines the columns of the grid, and their properties. It is an array of objects, each object representing a column.

Here is an example with a complete column definitions object:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';consttruncate=(str:string,n:number)=>{returnstr.length>n?str.slice(0,n-1)+'...':str;};exportconstPostList=()=>{constcolumnDefs=[{field:'id',editable:false,headerCheckboxSelection:true,checkboxSelection:true,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at',headerName:'Publication Date',},{field:'body',cellRenderer:({value})=>truncate(value,20),},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

DatagridAGClient custom columnDefs

Have a look atthe ag-grid documentation for the exhaustive list of column properties.

darkTheme

You can use a different dark theme for the grid by passing adarkTheme prop. It will be applied automatically whenever React Admin theme is set to dark.You can for instance use one of thethemes provided by ag-grid, likeag-theme-balham orag-theme-alpine-dark:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-balham.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}theme="ag-theme-balham"darkTheme="ag-theme-balham-dark"/></List>);};

DatagridAGClient Dark

Tip: Remember to import the corresponding stylesheet (e.g.ag-theme-balham[.min].css forag-theme-balham).

defaultColDef

ThedefaultColDef prop allows you to define default properties for all columns. It is an object with the same properties ascolumnDefs objects.

In the example below, we enable flex mode on the columns, and set each column to take 1/3 of the available space:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constdefaultColDef={flex:1,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

DatagridAGClient defaultColDef

mutationOptions

You can use themutationOptions prop to provide options to thedataProvider.update() call triggered when a cell or a row is edited.

In particular, this allows to choose themutationMode, and/or to pass ameta object to the dataProvider.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}mutationOptions={{meta:{foo:'bar'},mutationMode:'optimistic',}}/></List>);};

This also allows to display a notification after the mutation succeeds.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,useNotify}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constnotify=useNotify();constonSuccess=React.useCallback(()=>{notify('ra.notification.updated',{type:'info',messageArgs:{smart_count:1,},undoable:true,});},[notify]);return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}mutationOptions={{mutationMode:'undoable',onSuccess,}}/></List>);};

pagination

By default, thepagination prop is set totrue, so that the records are paginated.

If you would like to view all the records at once, you can set thepagination prop tofalse. Thanks toag-grid’s DOM virtualization, you will be able to scroll across all of them with no performance issues.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';constCarList=()=>{constcolumnDefs=[{field:'make'},{field:'model'},{field:'price'},];constdefaultColDef={flex:1,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}pagination={false}/></List>);};

If you have subscribed to theEnterprise version of ag-grid, you can also add aStatus Bar to show the total number of rows.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReact,{useMemo}from'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';import'ag-grid-enterprise';constCarList=()=>{conststatusBar=useMemo(()=>{return{statusPanels:[{statusPanel:'agTotalAndFilteredRowCountComponent',align:'left',},],};},[]);constcolumnDefs=[{field:'make'},{field:'model'},{field:'price'},];constdefaultColDef={flex:1,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}pagination={false}statusBar={statusBar}/></List>);};

DatagridAGClient with status bar

preferenceKey

<DatagridAGClient> will store thegridState in theStore, under the key${resource}.ag-grid.params.grid. ThisgridState persisted in the store is applied once when the grid is created, it means that users will find the grid as they left it previously.

If you wish to change the key used to store the columns order and size, you can pass apreferenceKey prop to<DatagridAGClient>.

<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}preferenceKey="my-post-list"/></List>

If, instead, you want to disable the persistence of the columns order and size, you can passfalse to thepreferenceKey prop:

<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}preferenceKey={false}/></List>

Tip: If you update thecolumnDefs prop, make sure to clear orinvalidate the React-admin store in order to view your changes.

sx

You can also usethesx prop to customize the grid’s style:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}sx={{'& .ag-header-cell-comp-wrapper':{color:'red'}}}/></List>);};

DatagridAGClient sx

It can also be helpful to change the default grid’s height (calc(100vh - 96px - ${theme.spacing(1)})):

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[/* ... */];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}sx={{height:'calc(100vh - 250px)'}}/></List>);};

DatagridAGClient sx height

theme

You can use a different theme for the grid by passing atheme prop. You can for instance use one of thethemes provided by ag-grid, likeag-theme-balham orag-theme-alpine-dark:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-balham.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}theme="ag-theme-balham"/></List>);};

DatagridAGClient Dark

Tip: Remember to import the corresponding stylesheet (e.g.ag-theme-balham[.min].css forag-theme-balham).

AgGrid Defaults

Under the hood,<DatagridAGClient> is a wrapper around<AgGridReact>. However, it sets some important default values:

  • pagination is set totrue
  • paginationAutoPageSize is set totrue
  • animateRows is set totrue
  • rowSelection is set to'multiple'
  • suppressRowClickSelection is set totrue
  • readOnlyEdit is set totrue
  • getRowId is set to use the recordid field

It also register the following defaultmodules:ClientSideRowModelModule,CommunityFeaturesModule andCsvExportModule. If you wish to add custom modules, make sure you have at least theClientSideRowModelModule:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';import{ClientSideRowModelModule}from'@ag-grid-community/client-side-row-model';import{CsvExportModule}from'@ag-grid-community/csv-export';import{ClipboardModule}from'@ag-grid-enterprise/clipboard';constmodules=[ClientSideRowModelModule,CsvExportModule,ClipboardModule];exportconstPostList=()=>{constcolumnDefs=[{field:'id',editable:false,headerCheckboxSelection:true,checkboxSelection:true,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at',headerName:'Publication Date',},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}modules={modules}/></List>);};

It also includes adefaultColDef object with the following properties:

{resizable:true,filter:true,sortable:true,editable:true,headerCheckboxSelectionFilteredOnly:true,headerCheckboxSelectionCurrentPageOnly:true,}

You may override any of these defaults by passing the corresponding props to<DatagridAGClient> (defaultColDef will be merged with the defaults).

Accessing The Grid API

You can access the grid’sapi by passing aref to<DatagridAGClient>.

In this example, we use theapi to automatically resize all columns to fit their content on first render:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{AgGridReact}from'ag-grid-react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}ref={gridRef}onFirstDataRendered={onFirstDataRendered}/></List>);};

Check out theGrid API documentations to learn more.

Changing The Default Column Width

By default, ag-grid will render each column with a fixed size.

You can choose to enable flex mode by setting theflex prop either on thecolumnDefs or on thedefaultColDef:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at',flex:1},{field:'body'},];constdefaultColDef={flex:2,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

DatagridAGClient flex

Alternatively, you can use the grid’sapi to callautoSizeAllColumns to automatically resize all columns to fit their content:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{AgGridReact}from'ag-grid-react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}ref={gridRef}onFirstDataRendered={onFirstDataRendered}/></List>);};

DatagridAGClient auto size

Check out theColumn Sizing documentation for more information and more alternatives.

Selecting Rows And Enabling Bulk Actions

Just like<Datagrid>,<DatagridAGClient> supports row selection and bulk actions.

Add a column with the following definition to enable row selection:

{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},

Below is an example with thePostList component:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

DatagridAGClient selected rows

Just like with<Datagrid>, you can customize the bulk actions by passing abulkActionButtons prop to<DatagridAGClient>.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List,BulkExportButton,BulkDeleteButton}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';constPostBulkActionButtons=()=>(<><BulkExportButton/><BulkDeleteButton/></>);exportconstPostList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title'},{field:'published_at'},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}bulkActionButtons={<PostBulkActionButtons/>}/></List>);};

Enabling Infinite Pagination

By default,<DatagridAGClient> renders pagination controls at the bottom of the list. You can disable these controls to switch to an infinite pagination mode, where the grid shows the next rows on scroll. Thanks toag-grid’s DOM virtualization, this mode causes no performance problem.

To enable infinite pagination, set thepagination prop tofalse.

import'ag-grid-community/styles/ag-grid.css';import'ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';constCarList=()=>{constcolumnDefs=[{field:'make'},{field:'model'},{field:'price'},];constdefaultColDef={flex:1,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}pagination={false}/></List>);};

If you have subscribed to theEnterprise version of ag-grid, you can also add aStatus Bar to show the total number of rows.

DatagridAGClient with status bar

import'ag-grid-community/styles/ag-grid.css';import'ag-grid-community/styles/ag-theme-alpine.css';importReact,{useMemo}from'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';import'ag-grid-enterprise';constCarList=()=>{conststatusBar=useMemo(()=>{return{statusPanels:[{statusPanel:'agTotalAndFilteredRowCountComponent',align:'left',},],};},[]);constcolumnDefs=[{field:'make'},{field:'model'},{field:'price'}];constdefaultColDef={flex:1};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}pagination={false}statusBar={statusBar}/></List>);};

Enabling Full Row Edition

By default, editing is enabled on cells, which means you can edit a cell by double-clicking on it, and it will trigger a call to the dataProvider’supdate function.

DatagridAGClient edit cell

However, if you’d like to update the full row at once instead, you can enable full row editing by passingeditType="fullRow" to<DatagridAGClient>:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[/* ... */];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}editType="fullRow"/></List>);};

DatagridAGClient edit row

Disabling Cell Edition

Seteditable: false in the definition of a column to disable the ability to edit its cells.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at',editable:false},{field:'body'},];return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}/></List>);};

Alternatively, you can disable the ability to edit all cells by passingeditable: false to thedefaultColDef:

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constcolumnDefs=[{field:'title'},{field:'published_at'},{field:'body'},];constdefaultColDef={editable:false,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}/></List>);};

Using AG Grid Enterprise

<DatagridAGClient> is also compatible with theEnterprise version of ag-grid.

You can follow the instructions in theGetting Started with AG Grid Enterprise section of theGetting Started documentation to enable the Enterprise features.

Below is a short example of what you can achieve.

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';import{AgGridReact}from'ag-grid-react';import'ag-grid-enterprise';importReactfrom'react';import{List}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';constOlympicWinnersList=()=>{constcolumnDefs=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'athlete'},{field:'age'},{field:'country'},{field:'year'},{field:'date'},{field:'sport'},{field:'gold'},{field:'silver'},{field:'bronze'},{field:'total'},];constgridRef=React.useRef<AgGridReact>(null);constonFirstDataRendered=React.useCallback(()=>{gridRef.current.api.autoSizeAllColumns();},[]);constdefaultColDef={enableRowGroup:true,};return(<ListperPage={10000}pagination={false}><DatagridAGClientcolumnDefs={columnDefs}defaultColDef={defaultColDef}ref={gridRef}onFirstDataRendered={onFirstDataRendered}rowGroupPanelShow="always"groupSelectsChildren/></List>);};

Adding An Expandable Panel (Master/Detail)

You can leverageag-grid Master Detail Module to add an expandable panel.

For instance, here’s how to show the comments of a post in an expandable panel:

DatagridAGClient Master Detail

import'@ag-grid-community/styles/ag-grid.css';import'@ag-grid-community/styles/ag-theme-alpine.css';import{AgGridReact}from'ag-grid-react';import{ColDef,CommunityFeaturesModule}from'@ag-grid-community/core';import{ClientSideRowModelModule}from'@ag-grid-community/client-side-row-model';import{CsvExportModule}from'@ag-grid-community/csv-export';import{MasterDetailModule}from'@ag-grid-enterprise/master-detail';importReactfrom'react';import{List,useDataProvider,useNotify}from'react-admin';import{DatagridAGClient}from'@react-admin/ra-datagrid-ag';exportconstPostList=()=>{constdataProvider=useDataProvider();constnotify=useNotify();constcolumnDefs:ColDef<any,any>[]=[{headerCheckboxSelection:true,checkboxSelection:true,editable:false,minWidth:48,maxWidth:48,suppressColumnsToolPanel:true,suppressHeaderFilterButton:true,},{field:'title',flex:1,cellRenderer:'agGroupCellRenderer'},{field:'published_at'},];constdetailCellRendererParams={// provide the Grid Options to use on the Detail GriddetailGridOptions:{columnDefs:[{field:'body',flex:1},{field:'author.name'}],},// get the rows for each Detail GridgetDetailRowData:params=>{dataProvider.getManyReference('comments',{target:'post_id',id:params.data.id,pagination:{page:1,perPage:100},sort:{field:'created_at',order:'DESC'},filter:{},}).then(({data})=>{params.successCallback(data);}).catch(error=>{notify(error.message,{type:'error'});params.successCallback([]);});},};return(<Listresource="posts"pagination={false}><DatagridAGClientmasterDetailcolumnDefs={columnDefs}detailCellRendererParams={detailCellRendererParams}pagination={false}modules={[ClientSideRowModelModule,CommunityFeaturesModule,CsvExportModule,MasterDetailModule,]}/></List>);};

[8]ページ先頭

©2009-2025 Movatter.jp