### Basic Dash AG Grid Setup Source: https://github.com/plotly/dash-ag-grid/blob/main/README.md Installs the dash-ag-grid package and sets up a basic AG Grid with default features. This example reads data from a CSV and displays it in a grid. ```python import dash_ag_grid as dag from dash import Dash import pandas as pd app = Dash() df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/space-mission-data.csv") app.layout = dag.AgGrid( rowData=df.to_dict("records"), columnDefs=[{"field": i} for i in df.columns], ) app.run(debug=True) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/plotly/dash-ag-grid/blob/main/CONTRIBUTING.md Install Dash with development and testing extras to set up your environment for contributing. ```bash pip install dash[dev,testing] ``` -------------------------------- ### Install dash-ag-grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/README.md Install the dash-ag-grid package using pip. ```bash pip install dash-ag-grid ``` -------------------------------- ### Basic Grid with Sorting and Filtering Example Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md An example demonstrating how to create a basic AG Grid with sorting and filtering enabled. ```APIDOC ### Example: Basic Grid with Sorting and Filtering ```python import dash_ag_grid as dag from dash import Dash, html import pandas as pd app = Dash(__name__) df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/space-mission-data.csv") app.layout = html.Div([ dag.AgGrid( id="space-grid", rowData=df.to_dict("records"), columnDefs=[{"field": col} for col in df.columns], defaultColDef={ "sortable": True, "filter": True, "resizable": True, "minWidth": 100, }, columnSize="responsiveSizeToFit", className="ag-theme-alpine" ) ], style={"margin": 20}) if __name__ == "__main__": app.run_server(debug=True) ``` ``` -------------------------------- ### Column Sizing Example in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of configuring responsive column sizing in Dash AG Grid, setting default and specific min/max widths for columns. ```python dag.AgGrid( columnSize="responsiveSizeToFit", columnSizeOptions={ "defaultMinWidth": 100, "defaultMaxWidth": 500, "columnLimits": [ {"key": "id", "minWidth": 50, "maxWidth": 100}, {"key": "name", "minWidth": 150, "maxWidth": 300} ] }, columnDefs=[...] ) ``` -------------------------------- ### Import and Setup Dash App Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Standard imports for Dash AG Grid and a basic Dash app initialization. ```python import dash_ag_grid as dag from dash import Dash, html, Input, Output, callback import pandas as pd app = Dash(__name__) ``` -------------------------------- ### Selection and Pinning Example Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md An example demonstrating how to configure row selection with header checkboxes and pin columns to the left and right sides of the grid. ```APIDOC ## Example: Selection and Pinning ```python columnDefs=[ { "checkboxSelection": True, "headerCheckboxSelection": True, "pinned": "left", "width": 50 }, {"field": "id", "pinned": "left", "width": 60}, {"field": "name", "flex": 1}, {"field": "email", "flex": 1}, {"field": "joinDate", "pinned": "right", "width": 120}, ] ``` ``` -------------------------------- ### Master-Detail Grid Example in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of setting up a master-detail grid in Dash AG Grid, including defining detail grid options and providing hierarchical row data. ```python dag.AgGrid( masterDetail=True, detailCellRendererParams={ "detailColName": "children", "suppressCallback": True, "detailGridOptions": { "columnDefs": [ {"field": "id"}, {"field": "name"} ], "defaultColDef": {"sortable": True, "filter": True} } }, rowData=[ { "id": 1, "name": "Parent", "children": [ {"id": 10, "name": "Child 1"}, {"id": 11, "name": "Child 2"} ] } ] ) ``` -------------------------------- ### Install Component in Development Mode Source: https://github.com/plotly/dash-ag-grid/blob/main/CONTRIBUTING.md Install the component in editable mode. This allows Python to use the files directly from the development directory, enabling live updates. ```bash pip install -e . ``` -------------------------------- ### Getting Grid API Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to obtain the Grid API object for interacting with the grid, both synchronously and asynchronously. ```APIDOC ## Synchronous API Access ### Description Get the Grid API object synchronously to call grid methods directly. ### Method Signature `dag.getApi(grid_id)` ### Example ```python api = dag.getApi("grid-id") api.selectAll() api.deselectAll() api.getSelectedRows() api.getDisplayedRowCount() api.resetColumnState() ``` ## Asynchronous API Access (Recommended) ### Description Get the Grid API object asynchronously, which is recommended for client-side callbacks. ### Method Signature `dash_ag_grid.getApiAsync(grid_id)` ### Example (Client-side JavaScript) ```javascript const api = await dash_ag_grid.getApiAsync('grid-id'); const count = api.getDisplayedRowCount(); ``` ``` -------------------------------- ### Editing Example with Params Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md Provides an example of configuring `cellEditorParams` for a text editor, including `maxLength` and `required` properties, and using `valueParser`. ```APIDOC ## Example: Editing ```python columnDefs=[ { "field": "email", "editable": True, "cellEditor": "agTextCellEditor", "cellEditorParams": { "maxLength": 50, "required": True }, "valueParser": { "function": "params.newValue?.trim() || params.oldValue" } } ] ``` ``` -------------------------------- ### Selection Patterns Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Examples of how to implement various row selection behaviors. ```APIDOC ## Select All / Deselect All ### Description Callbacks to trigger selecting or deselecting all rows in the grid. ### Select All Callback ```python @callback(Output("grid", "selectAll"), Input("select-all-btn", "n_clicks")) def select_all(n_clicks): return True ``` ### Deselect All Callback ```python @callback(Output("grid", "deselectAll"), Input("deselect-all-btn", "n_clicks")) def deselect_all(n_clicks): return True ``` ## Conditional Selection ### Description Select rows based on a condition, typically within a client-side callback. ### Example ```python @callback(Output("grid", "selectedRows"), Input("filter-btn", "n_clicks")) def select_filtered(n_clicks): return {"function": "params.data.status === 'active'"} ``` ## Select by IDs ### Description Select specific rows by providing a list of their IDs. ### Example ```python return {"ids": ["id-1", "id-2"]} ``` ``` -------------------------------- ### Complete Column Definition Example Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md This snippet shows a full example of column definitions for Dash AG Grid. It includes configurations for field identification, layout properties, user interaction, data display formatting, conditional styling, and enterprise-level features like aggregation. ```python columnDefs=[ { # Identification "field": "id", "headerName": "ID", "colId": "id", # Layout "width": 60, "pinned": "left", "sortable": True, # Selection "checkboxSelection": True, "headerCheckboxSelection": True, }, { # Identification "field": "name", "headerName": "Full Name", # Layout "flex": 2, "minWidth": 150, "wrapText": True, "autoHeaderHeight": True, # Interaction "sortable": True, "filter": "agTextColumnFilter", "editable": True, "cellEditor": "agTextCellEditor", "cellEditorParams": {"maxLength": 100}, # Display "headerTooltip": "Enter customer full name", "tooltip": "{value}", }, { # Identification "field": "joinDate", "headerName": "Join Date", # Layout "width": 120, # Interaction "sortable": True, "filter": "agDateColumnFilter", "editable": True, "cellEditor": "agDateCellEditor", # Display "valueFormatter": { "function": "d3.timeFormat('%Y-%m-%d')(new Date(params.value))" }, # Styling "cellStyle": { "styleConditions": [ { "condition": "new Date(params.value).getFullYear() < 2020", "style": {"color": "#999"} } ] } }, { # Identification "field": "revenue", "headerName": "Revenue", "type": "numericColumn", # Layout "width": 120, # Display "valueFormatter": { "function": "d3.format('$,.2f')(params.value)" }, # Styling "cellStyle": { "styleConditions": [ { "condition": "params.value > 100000", "style": {"color": "green", "fontWeight": "bold"} }, { "condition": "params.value < 50000", "style": {"color": "red"} } ] }, # Enterprise "aggFunc": "sum", } ] ``` -------------------------------- ### Initialize AgGrid Component Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Basic initialization of the AgGrid component with row data and column definitions. This example demonstrates how to set up a simple grid with static data and responsive column sizing. ```python import dash_ag_grid as dag from dash import Dash, html app = Dash(__name__) app.layout = html.Div([ dag.AgGrid( id="my-grid", rowData=[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}], columnDefs=[ {"field": "name"}, {"field": "age"} ], columnSize="responsiveSizeToFit" ) ]) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Example: Value Formatting and Getter Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md Demonstrates how to format cell values for display using `valueFormatter` and compute display values using `valueGetter`. The `valueFormatter` uses d3.format for currency, and `valueGetter` calculates a percentage. ```python columnDefs=[ { "field": "price", "valueFormatter": { "function": "d3.format('$.2f')(params.value)" } }, { "field": "profit_margin", "valueGetter": { "function": "(params.data.profit / params.data.revenue * 100).toFixed(2) + '%' } } ] ``` -------------------------------- ### Minimal Dash AG Grid Example Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md A basic Dash AG Grid component with minimal row data and column definitions. ```python dag.AgGrid( id="grid", rowData=[{"name": "Alice", "age": 25}], columnDefs=[{"field": "name"}, {"field": "age"}] ) ``` -------------------------------- ### Row Styling Example in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Demonstrates applying conditional background colors and font weights to rows based on age and status using the `getRowStyle` prop. ```python dag.AgGrid( getRowStyle={ "styleConditions": [ { "condition": "params.data.age < 18", "style": {"backgroundColor": "#ffcccc", "fontWeight": "bold"} }, { "condition": "params.data.status === 'active'", "style": {"backgroundColor": "#ccffcc"} } ], "defaultStyle": {"backgroundColor": "white"} }, rowData=[...] ) ``` -------------------------------- ### Display Dash AG Grid and AG Grid Community Versions Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/configuration.md Print the installed versions of the Dash AG Grid library and the AG Grid community module it uses. ```python from dash_ag_grid._version import __version__, grid_version print(f"Dash AG Grid: {__version__}") print(f"AG Grid Community: {grid_version}") ``` -------------------------------- ### Dash AG Grid: CSV Export Parameter Examples Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Illustrates valid and invalid configurations for CSV export parameters. Avoid referencing non-existent columns and ensure valid file names and options. ```python # ❌ Invalid column key { "columnKeys": ["nonexistent_col"] } ``` ```python # ✅ Valid export config { "fileName": "export.csv", "columnSeparator": ",", "skipColumnHeaders": False, "onlySelected": True } ``` -------------------------------- ### Build Dash AG Grid Component Source: https://github.com/plotly/dash-ag-grid/blob/main/CONTRIBUTING.md Build the component from the root of the repository after installing dependencies. This command compiles the React components into Python code. ```bash npm i npm run build ``` -------------------------------- ### Basic Grid with Sorting and Filtering in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Demonstrates how to create a basic AG Grid with sorting and filtering enabled. Ensure you have pandas and dash-ag-grid installed. The grid is configured to be responsive and uses the 'ag-theme-alpine' theme. ```python import dash_ag_grid as dag from dash import Dash, html import pandas as pd app = Dash(__name__) df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/space-mission-data.csv") app.layout = html.Div([ dag.AgGrid( id="space-grid", rowData=df.to_dict("records"), columnDefs=[{"field": col} for col in df.columns], defaultColDef={ "sortable": True, "filter": True, "resizable": True, "minWidth": 100, }, columnSize="responsiveSizeToFit", className="ag-theme-alpine" ) ], style={"margin": 20}) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Master-Detail Grid Setup Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Configures a Dash AG Grid component to enable master-detail functionality. This allows parent rows to expand and show nested child rows. ```python dag.AgGrid( masterDetail=True, detailCellRendererParams={ "suppressCallback": True, "detailColName": "children", "detailGridOptions": {...} }, rowData=[ { "id": 1, "name": "Parent", "children": [{"id": 10, "name": "Child"}] } ] ) ``` -------------------------------- ### Dash AG Grid with Row Selection Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/README.md Shows how to implement row selection in Dash AG Grid and display the selected rows. This example requires a callback to update the UI based on user selection. ```python import dash_ag_grid as dag from dash import Dash, html, Input, Output, callback app = Dash(__name__) app.layout = html.Div([ dag.AgGrid( id="grid", rowData=[ {"id": 1, "name": "Alice", "age": 25}, {"id": 2, "name": "Bob", "age": 30}, ], columnDefs=[ {"field": "id"}, {"field": "name"}, {"field": "age"} ], rowSelection="multiple", defaultColDef={"sortable": True, "filter": True}, ), html.Div(id="selection-output") ]) @callback( Output("selection-output", "children"), Input("grid", "selectedRows") ) def show_selected(selected): if not selected: return "No rows selected" names = [row["name"] for row in selected] return f"Selected: {', '.join(names)}" if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Get Grid API (Synchronous) Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Retrieve the grid's API object synchronously to interact with grid methods. Use this for immediate actions after the grid is initialized. ```python api = dag.getApi("grid-id") api.selectAll() api.deselectAll() api.getSelectedRows() api.getDisplayedRowCount() api.resetColumnState() ``` -------------------------------- ### Event Listener Callback in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of a Dash callback that logs event data received from the 'eventData' prop of an AG Grid component. ```python @callback( Output("event-log", "children"), Input("grid", "eventData") ) def on_event(event): if not event: return "No events" return f"Event at {event['timestamp']}: {event['data']}" ``` -------------------------------- ### Python: Safe Wrapped Function Format (No Return) Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Provides an example of the recommended wrapped function format for AG Grid properties, where the 'return' keyword is often not needed within the JavaScript function string. ```python { "field": "price", "valueFormatter": { "function": "params.value * 1.10" # No 'return' needed } } ``` -------------------------------- ### Registering Custom Functions with Dash AG Grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/renderers.md Demonstrates how to register custom JavaScript functions globally in `window.dashAgGridFunctions` for use in column definitions, such as `valueFormatter`. This example registers `double` and `greet` functions. ```python import dash from dash import html, Dash import dash_ag_grid as dag app = Dash(__name__) app.layout = html.Div([ html.Script(""" window.dashAgGridFunctions = { double: function(x) { return x * 2; }, greet: function(name) { return 'Hello, ' + name; } }; """), dag.AgGrid( id="grid", rowData=[{"value": 5}], columnDefs=[ { "field": "value", "valueFormatter": "{function: 'double(params.value)'}" } ] ) ]) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Built-in Editors Example Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md Demonstrates the use of various built-in cell editors for different data types, such as text, number, checkbox, select, and date editors. ```APIDOC ## Built-in Editors ```python columnDefs=[ {"field": "name", "editable": True, "cellEditor": "agTextCellEditor"}, {"field": "age", "editable": True, "cellEditor": "agNumberCellEditor"}, {"field": "active", "editable": True, "cellEditor": "agCheckboxCellEditor"}, { "field": "status", "editable": True, "cellEditor": "agSelectCellEditor", "cellEditorParams": {"values": ["active", "inactive", "pending"]} }, {"field": "joinDate", "editable": True, "cellEditor": "agDateCellEditor"}, ] ``` ``` -------------------------------- ### Registering Custom Components with Dash AG Grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/renderers.md Shows how to register custom JavaScript cell renderers globally in `window.dashAgGridComponentFunctions`. This example defines a `MyRenderer` class with `init`, `getGui`, and `refresh` methods. ```javascript html.Script(""" window.dashAgGridComponentFunctions = { myCustomRenderer: class MyRenderer { init(params) { this.params = params; } getGui() { const el = document.createElement('div'); el.textContent = 'Custom: ' + this.params.value; return el; } refresh() { return true; } } }; """), ``` -------------------------------- ### Python: Enabling `dangerously_allow_code` with `toFixed` Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Another example of enabling `dangerously_allow_code=True` to use raw JavaScript, this time with the `toFixed` method. Remember to only use this for trusted code sources. ```python dag.AgGrid( dangerously_allow_code=True, # Only for trusted sources! columnDefs=[ { "field": "price", "valueFormatter": "params.value.toFixed(2)" } ] ) ``` -------------------------------- ### Dash AG Grid Property Mapping Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md This table outlines common Dash AG Grid properties, their types, when they trigger callbacks, and provides example usage within Dash callbacks. ```python @callback(Output("grid", "rowData")) ``` ```python @callback(Output("grid", "columnDefs")) ``` ```python Input("grid", "selectedRows") ``` ```python Input("grid", "cellClicked") ``` ```python Input("grid", "cellDoubleClicked") ``` ```python Input("grid", "cellValueChanged") ``` ```python @callback(Output("grid", "rowTransaction")) ``` ```python Input("grid", "columnState") ``` ```python Input("grid", "filterModel") ``` ```python Input("grid", "selectedRows") ``` ```python Input("grid", "virtualRowData") ``` ```python @callback(Output("grid", "paginationGoTo")) ``` ```python @callback(Output("grid", "csvExportParams")) ``` ```python Input("grid", "getRowsRequest") ``` ```python @callback(Output("grid", "getRowsResponse")) ``` ```python @callback(Output("grid", "scrollTo")) ``` -------------------------------- ### Configure CSV Export Parameters in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of a Dash callback that sets CSV export parameters. It specifies a filename, column separator, and whether to export only selected rows. ```python from dash import callback, Output, Input @callback( Output("grid", "csvExportParams"), Input("export-btn", "n_clicks"), prevent_initial_call=True ) def export_data(n_clicks): return { "fileName": "export.csv", "columnSeparator": ";", "onlySelected": True, "skipColumnHeaders": False } ``` -------------------------------- ### Attach Event Listeners to AG Grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Configure `eventListeners` during grid initialization to attach custom JavaScript event handlers. This example shows how to listen for row clicks, cell focus, and column changes, updating Dash outputs with event data. ```python import dash_ag_grid as dag from dash import callback, Output, Input dag.AgGrid( id="grid", rowData=..., columnDefs=..., eventListeners={ "onRowClicked": ["{function: 'function(event) { setEventData({message: \"Row clicked: \" + event.data.id}); }'}"], "onCellFocused": ["{function: 'function(event) { console.log(\"Focus on:\", event.column.colId); }'}"], "onDisplayedColumnsChanged": ["{function: 'function(event) { setGridProps({columnState: api.columnController.getColumnState()}); }'}"] } ) @callback( Output("event-output", "children"), Input("grid", "eventData") ) def on_event(event_data): if not event_data: return "No events" return f"Event: {event_data['data']}" ``` -------------------------------- ### Get AG Grid API Asynchronously Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Use `getApiAsync` to retrieve the AG Grid API instance, especially when the grid might not be initialized yet. It retries with exponential backoff for up to 120 seconds. This example shows how to get the API in a client-side callback to fetch the displayed row count. ```python import dash_ag_grid as dag from dash import Dash, html, callback, Input, Output, clientside_callback import json app = Dash(__name__) app.layout = html.Div([ dag.AgGrid( id="my-grid", rowData=[{"id": 1, "name": "Alice"}], columnDefs=[{"field": "id"}, {"field": "name"}], ), html.Button("Get Row Count", id="get-count-btn"), html.Div(id="count-output"), ]) # Client-side callback using async API app.clientside_callback( """ async function(n_clicks) { if (!n_clicks) return ''; try { const api = await dash_ag_grid.getApiAsync('my-grid'); const count = api.getDisplayedRowCount(); return `Grid has ${count} rows`; } catch (err) { return `Error: ${err.message}`; } } """, Output("count-output", "children"), Input("get-count-btn", "n_clicks"), prevent_initial_call=True ) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Accessing Grid API Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Illustrates how to set up a basic grid and includes a placeholder for a callback that would typically interact with the grid's API. Client-side callbacks are recommended for direct API interactions. ```python import dash_ag_grid as dag from dash import Dash, html, Input, Output, callback, clientside_callback, ALL import json app = Dash(__name__) app.layout = html.Div([ dag.AgGrid( id="my-grid", rowData=[{"name": "Alice", "age": 25}], columnDefs=[{"field": "name"}, {"field": "age"}], ), html.Button("Select All", id="select-all-btn"), ]) @callback( Input("select-all-btn", "n_clicks"), prevent_initial_call=True ) def select_all(n_clicks): # Client-side approach recommended for API calls pass if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Grid with Row Selection and Callbacks Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Demonstrates setting up a grid with multiple row selection enabled and a callback to display the number of selected rows. ```python import dash_ag_grid as dag from dash import Dash, html, Input, Output, callback import pandas as pd app = Dash(__name__) df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv") app.layout = html.Div([ dag.AgGrid( id="olympic-grid", rowData=df.to_dict("records"), columnDefs=[{"field": col} for col in df.columns], rowSelection="multiple", defaultColDef={"sortable": True, "filter": True}, ), html.Div(id="selected-rows-output") ]) @callback( Output("selected-rows-output", "children"), Input("olympic-grid", "selectedRows") ) def update_output(selected_rows): return f"Selected {len(selected_rows)} rows" if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Column Filter Types Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md Examples of enabling different built-in filter types for columns. ```python # Text filter {"field": "name", "filter": "agTextColumnFilter"} ``` ```python # Number filter {"field": "age", "filter": "agNumberColumnFilter"} ``` ```python # Date filter {"field": "joinDate", "filter": "agDateColumnFilter"} ``` ```python # Set filter {"field": "status", "filter": "agSetColumnFilter"} ``` ```python # Multiline text filter {"field": "notes", "filter": "agMultiColumnFilter"} ``` -------------------------------- ### AgGrid Component Usage Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Demonstrates the basic initialization of the AgGrid component with row data and column definitions. ```APIDOC ## AgGrid Component ### Description The `AgGrid` component is the primary interface for integrating the AG Grid JavaScript library into Dash applications. It allows for displaying, editing, and interacting with tabular data. ### Constructor / Initialization ```python import dash_ag_grid as dag from dash import Dash, html app = Dash(__name__) app.layout = html.Div([ dag.AgGrid( id="my-grid", rowData=[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}], columnDefs=[ {"field": "name"}, {"field": "age"} ], columnSize="responsiveSizeToFit" ) ]) if __name__ == "__main__": app.run_server(debug=True) ``` ### Core Properties #### Data Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `rowData` | array of objects | `[]` | The data rows to display in the grid | | `columnDefs` | array of objects | `undefined` | Column definitions specifying field names, headers, renderers, and behavior | | `defaultColDef` | object | `undefined` | Default settings applied to all columns | | `rowModelType` | string: `'clientSide' | 'infinite' | 'viewport' | 'serverSide'` | `'clientSide'` | Specifies the row model type for data loading strategy | | `masterDetail` | boolean | `false` | Enable master-detail grid functionality | | `detailCellRendererParams` | object | `undefined` | Configuration for detail grid in master-detail mode | #### UI/Display Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `id` | string | `undefined` | Unique identifier for the component in Dash callbacks | | `className` | string | `''` | CSS classes to apply to the grid container, including AG Grid theme classes | | `style` | object | `undefined` | Inline CSS styles for the grid container | | `columnSize` | string: `'sizeToFit' | 'autoSize' | 'responsiveSizeToFit'` | `null` | Automatic column sizing strategy | | `columnSizeOptions` | object | `undefined` | Options for column sizing behavior including min/max widths | | `rowStyle` | object | `undefined` | CSS styles for rows | | `rowClass` | string | `undefined` | CSS classes for rows | | `rowClassRules` | object | `undefined` | Rules to conditionally apply CSS classes to rows | | `getRowStyle` | object | `undefined` | Dynamic row styling with conditions | #### Selection Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `selectedRows` | array | object | `[]` | Currently selected rows. Can be array of row objects, object with `function` string, or object with array of `ids` | | `selectAll` | boolean | object | `false` | Select all rows. Pass `{filtered: true}` to select only filtered rows | | `deselectAll` | boolean | `false` | Deselect all rows when set to true | #### Data Editing Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `cellValueChanged` | array of objects | `undefined` | Array of cell value changes fired by user edits | | `rowTransaction` | object | `undefined` | Transaction object with `add`, `update`, `remove` arrays for row updates | | `getRowId` | string | `undefined` | Function string to extract unique row identifier from row data | | `deleteSelectedRows` | boolean | `false` | Delete selected rows when set to true | #### Filtering & Sorting Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `filterModel` | object | `{}` | Current filter state of the grid | | `getRowsRequest` | object | `undefined` | Request parameters for server-side or infinite scroll row loading | | `getRowsResponse` | object | `undefined` | Response object with row data for server-side models | | `getDetailRequest` | object | `undefined` | Request when user opens a detail row in master-detail view | | `getDetailResponse` | array of objects | `undefined` | Row data for detail grid | #### Pagination Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `paginationInfo` | object | `undefined` | Current pagination state: `isLastPageFound`, `pageSize`, `currentPage`, `totalPages`, `rowCount` | | `paginationGoTo` | string | number | null | Navigate pagination: `'first' | 'last' | 'next' | 'previous'` or page number | ``` -------------------------------- ### Run Integration Tests Source: https://github.com/plotly/dash-ag-grid/blob/main/review_checklist.md Execute integration tests for the main functionality of your component. This command launches a sample Dash app in a browser to test the component's behavior. ```python python -m tests.test_render ``` -------------------------------- ### Detail Grid Options for Master-Detail Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Standard AG Grid options object that can be passed to the detail grid component in a master-detail setup. ```typescript { columnDefs?: object[], defaultColDef?: object, rowData?: object[], // ... any other AG Grid option } ``` -------------------------------- ### Basic Dash AG Grid Usage Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/README.md Demonstrates how to create a basic Dash AG Grid with data from a Pandas DataFrame. Ensure 'data.csv' is in the same directory. ```python import dash_ag_grid as dag from dash import Dash, html import pandas as pd app = Dash(__name__) # Load data df = pd.read_csv("data.csv") # Create grid app.layout = html.Div([ dag.AgGrid( id="my-grid", rowData=df.to_dict("records"), columnDefs=[{"field": col} for col in df.columns], columnSize="responsiveSizeToFit", defaultColDef={"sortable": True, "filter": True}, className="ag-theme-alpine" ) ], style={"height": "600px", "margin": "20px"}) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### Safe Properties in Dash AG Grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/renderers.md Shows examples of properties that are always safe and can be used directly as strings, such as `headerName`, `field`, and `sortable`. ```python # ✅ Both safe and work as strings { "headerName": "My Column", "field": "myField", "sortable": True, } ``` -------------------------------- ### Handle Grid Initialization Error in Python Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Demonstrates how to use a try-except block to catch potential errors when calling `getApi()` before the grid is fully initialized. This is useful for debugging or providing user feedback. ```python from dash import callback, Input, Output import dash_ag_grid as dag # ❌ This will cause an error if callback fires before grid is ready @callback( Output("output", "children"), Input("grid", "id") # Fires immediately ) def early_callback(grid_id): try: api = dag.getApi(grid_id) # Grid might not be ready! return f"Grid ready" except Exception as e: return f"Error: {str(e)}" ``` -------------------------------- ### Handle Cell Click Event in Dash Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of how to use the `cellClicked` event data in a Dash callback to display information about the clicked cell. ```python from dash import callback, Output, Input @callback( Output("output", "children"), Input("grid", "cellClicked") ) def on_cell_click(event): if event: return f"Clicked: {event['value']} at row {event['rowId']}" return "No cell clicked yet" ``` -------------------------------- ### Get Grid API (Asynchronous) Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/QUICK-REFERENCE.md Access the grid's API asynchronously, recommended for client-side callbacks. This ensures the API is available before attempting to use it. ```javascript const api = await dash_ag_grid.getApiAsync('grid-id'); const count = api.getDisplayedRowCount(); ``` -------------------------------- ### Import Dash AG Grid and Dash Components Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/configuration.md Import necessary libraries for creating a Dash application with Dash AG Grid. This includes the AgGrid component and core Dash modules. ```python import dash_ag_grid as dag from dash import Dash, html, dcc app = Dash(__name__) ``` -------------------------------- ### Programmatic Row Selection by ID or Condition Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Select rows programmatically based on specific criteria using the `selectedRows` property. This example selects rows where the 'status' is 'active'. ```python from dash import callback from dash.dependencies import Input, Output, State @callback( Output("grid", "selectedRows"), Input("select-active-btn", "n_clicks"), State("grid", "rowData"), prevent_initial_call=True ) def select_active_rows(n_clicks, all_data): if not all_data: return [] # Use function form to select rows matching criteria return { "function": "params.data.status === 'active'" } ``` -------------------------------- ### Fetch Detail Grid Data with Callback Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Use `getDetailRequest` and `getDetailResponse` to fetch and display data for master-detail views. The callback should handle the request object and return the detail data. ```python import dash from dash import callback, Output, Input app = dash.Dash(__name__) @callback( Output("grid", "getDetailResponse"), Input("grid", "getDetailRequest") ) def get_detail_data(request): if not request: return None parent_id = request["data"]["id"] # Fetch detail rows based on parent detail_data = fetch_detail_rows(parent_id) return detail_data def fetch_detail_rows(parent_id): # Simulated fetch return [ {"detail_id": 1, "detail_name": f"Detail for {parent_id}-1"}, {"detail_id": 2, "detail_name": f"Detail for {parent_id}-2"} ] ``` -------------------------------- ### Configure Master-Detail Grids Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/README.md Enable master-detail functionality to show expandable detail rows. Configure 'detailCellRendererParams' for the detail grid. ```python dag.AgGrid( masterDetail=True, detailCellRendererParams={ "detailColName": "children", "suppressCallback": True, "detailGridOptions": {...} }, rowData=[...] ) ``` -------------------------------- ### Generate Distribution Files Source: https://github.com/plotly/dash-ag-grid/blob/main/CONTRIBUTING.md Create source and wheel distributions for the package after updating versions and rebuilding. This command populates the 'dist/' folder. ```bash npm run dist ``` -------------------------------- ### Auto-Save Grid Changes Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Implement an auto-save feature by triggering a callback when cell values change. This example uses `cellValueChanged` to capture changes and `rowData` to send the updated data for saving. ```python from dash import callback, Output, Input, State @callback( Output("auto-save-status", "children"), Input("grid", "cellValueChanged"), State("grid", "rowData"), prevent_initial_call=True ) def auto_save(changes, row_data): if not changes or not row_data: return "No changes" try: # Save to server save_to_database(row_data) return "✓ Saved automatically" except Exception as e: return f"Error saving: {str(e)}" ``` -------------------------------- ### Master-Detail Grids in Dash AG Grid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/AgGrid.md Set up master-detail grids by enabling `masterDetail=True`. Configure the detail grid's options and specify the column containing the detail data. ```python dag.AgGrid( masterDetail=True, detailCellRendererParams={ "detailGridOptions": { "columnDefs": [{"field": "sub_id"}, {"field": "sub_name"}], "defaultColDef": {"sortable": True, "filter": True}, }, "detailColName": "detail_rows", # Column containing detail data "suppressCallback": True, # Use embedded data, not callbacks }, rowData=[ {"id": 1, "name": "Parent", "detail_rows": [{"sub_id": 1, "sub_name": "Child"}]} ], ) ``` -------------------------------- ### Scroll Grid to Specific Row with Callback Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Utilize the `scrollTo` property to programmatically scroll the grid. This example scrolls to a row based on button clicks, specifying row and column positions. ```python import dash from dash import callback, Output, Input, State app = dash.Dash(__name__) @callback( Output("grid", "scrollTo"), Input("scroll-btn", "n_clicks"), State("grid", "rowData"), prevent_initial_call=True ) def scroll_to_row(n_clicks, all_data): if not all_data: return None # Scroll to row at index n_clicks * 10 return { "rowIndex": min(n_clicks * 10, len(all_data) - 1), "rowPosition": "middle", "column": "name", "columnPosition": "start" } ``` -------------------------------- ### Default Column Definitions for AgGrid Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/configuration.md Apply default properties like sorting, filtering, and resizing to all columns in the AgGrid component. This example shows how to set these defaults and then define specific columns. ```python dag.AgGrid( defaultColDef={ "sortable": True, "filter": True, "resizable": True, "minWidth": 100, "wrapHeaderText": True, "autoHeaderHeight": True, }, columnDefs=[ {"field": "id"}, {"field": "name"}, {"field": "age"}, # All inherit from defaultColDef ] ) ``` -------------------------------- ### Enable Detailed Logging in Python Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Set up Python's logging module to display DEBUG level messages for more detailed error information. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Column Width Configuration Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/column-definitions.md Configures the sizing behavior of columns, including fixed widths, flexible sizing, minimum and maximum widths, and whether resizing is enabled. Use 'flex' for proportional sizing and 'resizable' to allow user adjustments. ```python columnDefs=[ {"field": "id", "width": 50}, {"field": "name", "flex": 2}, {"field": "email", "flex": 3, "minWidth": 200}, ] ``` -------------------------------- ### Handle Grid Initialization Error with Async Clientside Callback Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/errors.md Utilizes an asynchronous clientside callback with a timeout to safely retrieve the grid API. This is the recommended approach for ensuring the grid is ready before interacting with its API. ```javascript app.clientside_callback( """ async function() { try { const api = await dash_ag_grid.getApiAsync('my-grid'); return 'Grid is ready!'; } catch(err) { return 'Grid initialization timeout'; } } """, Output("output", "children"), Input("grid-ready-check", "n_clicks"), prevent_initial_call=True ) ``` -------------------------------- ### Update Row Data on Cell Value Change Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/types.md Example of a Dash callback that updates the grid's `rowData` based on `cellValueChanged` events. It iterates through changes and updates the corresponding row data. ```python from dash import callback, Output, Input, State @callback( Output("grid", "rowData"), Input("grid", "cellValueChanged"), State("grid", "rowData"), prevent_initial_call=True ) def update_data(changes, current_data): if not changes: return current_data # Update data with changes for change in changes: current_data[change["rowIndex"]][change["colId"]] = change["newValue"] return current_data ``` -------------------------------- ### Pagination Navigation Callbacks Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Implement navigation buttons (first, previous, next, last) and an input field to control pagination. The `paginationGoTo` property is used to set the target page. Note that the page input converts user input to a 0-based index. ```python app.layout = html.Div([ html.Div([ html.Button("First", id="first-btn"), html.Button("Previous", id="prev-btn"), html.Button("Next", id="next-btn"), html.Button("Last", id="last-btn"), dcc.Input(id="page-input", type="number", placeholder="Go to page..."), ]), dag.AgGrid( id="grid", dashGridOptions={"pagination": True, "paginationPageSize": 20}, rowData=..., columnDefs=..., ), html.Div(id="pagination-info") ]) @callback( Output("grid", "paginationGoTo"), [Input("first-btn", "n_clicks"), Input("prev-btn", "n_clicks"), Input("next-btn", "n_clicks"), Input("last-btn", "n_clicks")], prevent_initial_call=True ) def navigate_pages(first, prev, next, last): ctx = dash.callback_context if not ctx.triggered: return None button_id = ctx.triggered[0]["prop_id"].split(".")[0] mapping = { "first-btn": "first", "prev-btn": "previous", "next-btn": "next", "last-btn": "last" } return mapping[button_id] @callback( Output("grid", "paginationGoTo"), Input("page-input", "value"), prevent_initial_call=True ) def go_to_page(page_number): if page_number is None: return None return page_number - 1 # Convert to 0-based @callback( Output("pagination-info", "children"), Input("grid", "paginationInfo") ) def show_pagination(info): if not info: return "No pagination" return f"Page {info['currentPage'] + 1} of {info['totalPages']} ({info['rowCount']} rows)" ``` -------------------------------- ### Import Available AG Grid Theme URLs Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/configuration.md Import available CSS theme URLs from the `dash_ag_grid.themes` module. `themes.BASE` is required for base styles. ```python from dash_ag_grid import themes # Available CSS URLs themes.BASE # Base styles (required) themes.ALPINE # Alpine theme themes.BALHAM # Balham theme themes.MATERIAL # Material theme themes.QUARTZ # Quartz theme ``` -------------------------------- ### Detail Grid Data Request Source: https://github.com/plotly/dash-ag-grid/blob/main/_autodocs/api-reference/callbacks-interactivity.md Handles requests for detail grid data in a master-detail setup. It receives a request containing the parent row's ID and returns the corresponding detail rows. ```APIDOC ## Detail Grid Data Request ### Description Handles requests for detail grid data in a master-detail setup. It receives a request containing the parent row's ID and returns the corresponding detail rows. ### Properties - `getDetailRequest`: Input property to receive detail data requests. - `getDetailResponse`: Output property to send detail data. ### Example Usage ```python @callback( Output("grid", "getDetailResponse"), Input("grid", "getDetailRequest") ) def get_detail_data(request): if not request: return None parent_id = request["data"]["id"] # Fetch detail rows based on parent detail_data = fetch_detail_rows(parent_id) return detail_data def fetch_detail_rows(parent_id): # Simulated fetch return [ {"detail_id": 1, "detail_name": f"Detail for {parent_id}-1"}, {"detail_id": 2, "detail_name": f"Detail for {parent_id}-2"} ] ``` ```