### Clone Example Project Source: https://www.ag-grid.com/react-data-grid/server-side-operations-nodejs Clone the example project repository to get started. ```bash git clone https://github.com/ag-grid/ag-grid-server-side-nodejs-example.git ``` -------------------------------- ### Example Grid Setup with Loading Renderer Source: https://www.ag-grid.com/react-data-grid/component-loading-cell-renderer This example demonstrates a basic AG-Grid React setup using a server-side row model and configuring a loading cell renderer. The `onGridReady` callback is used to initialize the grid. ```javascript const GridExample = () => { const defaultColDef = useMemo(() => ({ flex: 1, minWidth: 100, }), []); const loadingCellRenderer = useMemo(() => 'loadingCellRenderer', []); const loadingCellRendererParams = useMemo(() => ({ loadingMessage: 'Loading Rows...' }), []); const onGridReady = useCallback((params) => { // Supply the server-side row model const datasource = { getRows: (params) => { console.log('asking for rows:', params.request.startRow, 'to', params.request.endRow); // At this point, you would call your server to get the data. For this example, we'll simulate a delay. setTimeout(() => { const rowsThisPage = []; const lastRow = -1; params.successCallback(rowsThisPage, lastRow); }, 500); } }; params.api.setServerSideDatasource(datasource); }, []); return ( ); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` ``` -------------------------------- ### React Grid Example Setup Source: https://www.ag-grid.com/react-data-grid/find This snippet shows the basic setup for a React data grid using AG-Grid. It includes essential props like column definitions, search values, and event handlers. ```jsx import React, { StrictMode, } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact } from "ag-grid-react"; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-alpine.css"; const GridExample = () => { const columnDefs = [ { field: "make" }, { field: "model" }, { field: "price" }, ]; const findSearchValue = ""; const onGridReady = (params) => { console.log("Grid is ready"); }; const onFindChanged = (event) => { console.log("Find changed:", event.value); }; return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Complete AG-Grid React Example Source: https://www.ag-grid.com/react-data-grid/getting-started A full example demonstrating the setup of AG-Grid React, including module provisioning, component rendering, row and column definitions, and default column settings. ```javascript 'use client'; import React, { StrictMode, useState } from "react"; import { createRoot } from "react-dom/client"; import { AllCommunityModule } from "ag-grid-community"; import { AgGridProvider, AgGridReact } from "ag-grid-react"; // Create new GridExample component const GridExample = () => { // Row Data: The data to be displayed. const [rowData, setRowData] = useState([ { make: "Tesla", model: "Model Y", price: 64950, electric: true }, { make: "Ford", model: "F-Series", price: 33850, electric: false }, { make: "Toyota", model: "Corolla", price: 29600, electric: false }, { make: "Mercedes", model: "EQA", price: 48890, electric: true }, { make: "Fiat", model: "500", price: 15774, electric: false }, { make: "Nissan", model: "Juke", price: 20675, electric: false }, ]); // Column Definitions: Defines & controls grid columns. const [colDefs, setColDefs] = useState([ { field: "make" }, { field: "model" }, { field: "price" }, { field: "electric" }, ]); const defaultColDef = { flex: 1, }; // Container: Defines the grid's theme & dimensions. return (
); }; // Render GridExample const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Basic AG-Grid React Setup with Column Filter Source: https://www.ag-grid.com/react-data-grid/deep-dive This example demonstrates a full AG-Grid React setup, including fetching data and configuring a single column ('mission') to be filterable. ```javascript 'use client'; import { useFetchJson } from './useFetchJson'; // React Grid Logic import React, { StrictMode, useState } from "react"; import { createRoot } from "react-dom/client"; import { AllCommunityModule } from "ag-grid-community"; import { AgGridProvider, AgGridReact } from "ag-grid-react"; // Create new GridExample component const GridExample = () => { // Row Data: The data to be displayed. const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/space-mission-data.json", ); // Column Definitions: Defines & controls grid columns. const [colDefs] = useState([ { field: "mission", filter: true }, { field: "company" }, { field: "location" }, { field: "date" }, { field: "price" }, { field: "successful" }, { field: "rocket" }, ]); // Container: Defines the grid's theme & dimensions. return (
{/* The AG Grid component, with Row Data & Column Definition props */}
); }; // Render GridExample const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Example Grid Setup with Set Filters Source: https://www.ag-grid.com/react-data-grid/filter-set-filter-list This example demonstrates setting up AG-Grid React with two Set Filters: one using a static array for values and another using a callback that refreshes on open. ```javascript ("use client"); import React, useCallback, useMemo, useRef, useState, StrictMode, } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import "./styles.css"; import { ClientSideRowModelModule, ValidationModule } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, FiltersToolPanelModule, SetFilterModule, } from "ag-grid-enterprise"; import { getData } from "./data"; const modules = [ ClientSideRowModelModule, ColumnsToolPanelModule, FiltersToolPanelModule, ColumnMenuModule, ContextMenuModule, SetFilterModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const list1 = ["Elephant", "Lion", "Monkey"]; const list2 = ["Elephant", "Giraffe", "Tiger"]; const valuesArray = list1.slice(); let valuesCallbackList = list1; function valuesCallback(params) { setTimeout(() => { params.success(valuesCallbackList); }, 1000); } const arrayFilterParams = { values: valuesArray, }; const callbackFilterParams = { values: valuesCallback, refreshValuesOnOpen: true, }; const GridExample = () => { const gridRef = useRef(null); const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [rowData, setRowData] = useState(getData()); const [columnDefs, setColumnDefs] = useState([ { colId: "array", headerName: "Values Array", field: "animal", filter: "agSetColumnFilter", filterParams: arrayFilterParams, }, { colId: "callback", headerName: "Values Callback", field: "animal", ``` -------------------------------- ### Grid Example Component Setup Source: https://www.ag-grid.com/react-data-grid/row-dragging-to-external-dropzone Sets up the main React component for the grid example, including state for grid APIs, row data, and configuration. It defines the structure for two grids and a drop zone. ```javascript const GridExample = () => { const modules = useMemo(() => [ClientSideRowModelModule, RowGroupingModule, ColumnsToolPanelModule, FiltersToolPanelModule], []); const defaultColDef = useMemo(() => ({ width: 100, sortable: true, filter: true, floatingFilter: true, resizable: true, suppressNavigable: true }), []); const columns = useMemo(() => [ { field: 'id', rowDrag: true, width: 80 }, { field: 'color' }, { field: 'value' }, ], []); const rowClassRules = useMemo(() => ({ 'rag-element-red': params => params.data.color === 'Red', 'rag-element-green': params => params.data.color === 'Green', 'rag-element-blue': params => params.data.color === 'Blue', }), []); const getRowId = useCallback(params => params.data.id, []); const [leftRowData, setLeftRowData] = useState([ { id: 1, color: 'Red', value: 10 }, { id: 2, color: 'Green', value: 20 }, { id: 3, color: 'Blue', value: 30 }, ]); const [rightRowData, setRightRowData] = useState([ { id: 4, color: 'Red', value: 40 }, { id: 5, color: 'Green', value: 50 }, { id: 6, color: 'Blue', value: 60 }, ]); const [leftApi, setLeftApi] = useState(null); const [rightApi, setRightApi] = useState(null); const [eBin, setEBin] = useState(null); const [eBinIcon, setEBinIcon] = useState(null); const eLeftGrid = useRef(null); const eRightGrid = useRef(null); const dropSide = useRef('Right'); const addRecordToGrid = (side, data) => { const newData = { ...data, id: Math.random() }; if (side === 'left') { setLeftRowData([...leftRowData, newData]); } else { setRightRowData([...rightRowData, newData]); } }; const deleteRecord = (data) => { const id = data.id; setLeftRowData(leftRowData.filter(item => item.id !== id)); setRightRowData(rightRowData.filter(item => item.id !== id)); }; const addBinZone = (api) => { const dropZone = { getContainer: () => eBin, getIcon: () => { if (eBinIcon) { return eBinIcon; } return null; }, onDragStop: (dragParams) => { deleteRecord(dragParams.node.data); }, }; api.addRowDropZone(dropZone); }; const addGridDropZone = (dropSide, api) => { const dropZone = { getContainer: () => dropSide === "Right" ? eRightGrid.current : eLeftGrid.current, onDragStop: (dragParams) => addRecordToGrid(dropSide.toLowerCase(), dragParams.node.data), }; api.addRowDropZone(dropZone); }; useEffect(() => { if (rightApi && leftApi) { addBinZone(rightApi); addBinZone(leftApi); addGridDropZone("Right", rightApi); addGridDropZone("Left", leftApi); } }); const onGridReady = (side, params) => { if (side === "Left") { setLeftApi(params.api); } else { setRightApi(params.api); } }; const getAddRecordButton = (side, color) => ( ); const getInnerGridCol = (side) => (
{["Red", "Green", "Blue"].map((color) => getAddRecordButton(side, color), )}
onGridReady(side, params)} />
); return (
{getInnerGridCol("Left")}
{getInnerGridCol("Right")}
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Full AG-Grid Example with Row Numbers and Resizing Source: https://www.ag-grid.com/react-data-grid/row-numbers A comprehensive example demonstrating AG-Grid setup with Row Numbers enabled and row resizing activated. Includes necessary module imports and data fetching. ```javascript "use client"; import React, { useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { ClientSideRowModelModule, ValidationModule } from "ag-grid-community"; import { RowNumbersModule } from "ag-grid-enterprise"; import { useFetchJson } from "./useFetchJson"; const modules = [ ClientSideRowModelModule, RowNumbersModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete" }, { field: "country" }, { field: "sport" }, { field: "year" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, ]); const defaultColDef = useMemo(() => { return { flex: 1, minWidth: 100, }; }, []); const rowNumbers = useMemo(() => { return { enableRowResizer: true, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### AG-Grid React Setup with Initial Column Definitions Source: https://www.ag-grid.com/react-data-grid/column-updating-definitions Sets up AG-Grid React with initial column definitions, including initial width and sorting. This example demonstrates how to use initial attributes for column setup. ```javascript "use client"; import React, useCallback, useMemo, useRef, useState, StrictMode, } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import "./styles.css"; import { ClientSideRowModelModule, ColumnApiModule, ValidationModule, } from "ag-grid-community"; import { useFetchJson } from "./useFetchJson"; const modules = [ ColumnApiModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const getColumnDefs = () => { return [ { field: "athlete", initialWidth: 100, initialSort: "asc" }, { field: "age" }, { field: "country", initialPinned: "left" }, { field: "sport" }, { field: "year" }, { field: "date" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]; }; const GridExample = () => { const gridRef = useRef(null); const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const defaultColDef = useMemo(() => { return { initialWidth: 100, }; }, []); const [columnDefs, setColumnDefs] = useState(getColumnDefs()); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); const onBtWithDefault = useCallback(() => { gridRef.current.api.setGridOption("columnDefs", getColumnDefs()); }, []); const onBtRemove = useCallback(() => { gridRef.current.api.setGridOption("columnDefs", []); }, []); return (
); }; const root = createRoot(document.getElementById("root")); root.render( ``` -------------------------------- ### Full Example: Custom Theme and Grid Setup Source: https://www.ag-grid.com/react-data-grid/key-features A complete React component demonstrating how to set up AG Grid with a custom theme, modules, column definitions, and data fetching. This example integrates custom styling with grid functionality. ```jsx "use client"; import React, { useMemo, useRef, useState, useEffect, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { AllCommunityModule, themeQuartz } from "ag-grid-community"; import { useFetchJson } from "./useFetchJson"; const modules = [AllCommunityModule]; const myTheme = themeQuartz.withParams({ /* Low spacing = very compact */ spacing: 2, /* Changes the colour of the grid text */ foregroundColor: "rgb(14, 68, 145)", /* Changes the colour of the grid background */ backgroundColor: "rgb(241, 247, 255)", /* Changes the header colour of the top row */ headerBackgroundColor: "rgb(228, 237, 250)", /* Changes the hover colour of the row*/ rowHoverColor: "rgb(216, 226, 255)", }); const GridExample = () => { const gridRef = useRef(null); const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete", minWidth: 170 }, { field: "age" }, { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]); const theme = useMemo(() => { return myTheme; }, []); const defaultColDef = useMemo(() => { return { editable: true, filter: true, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Basic Grid Setup with Column Definitions Source: https://www.ag-grid.com/react-data-grid/column-headers-styling This snippet shows the basic setup for an Ag-Grid React component, including column definitions and default column properties. It's a foundational example for grid configuration. ```jsx const GridExample = () => { const columnDefs = [ // column definitions here ]; const defaultColDef = { flex: 1, minWidth: 100, }; const autoGroupColumnDef = { minWidth: 200, }; return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Database Setup Script Source: https://www.ag-grid.com/react-data-grid/server-side-operations-nodejs Run this SQL script to create the 'sample_data' database and the 'olympic_winners' table, populating it with data. ```bash mysql -u root -p -D sample_data < ./data/olympic_winners.sql ``` -------------------------------- ### Custom Row Drag Start Threshold Source: https://www.ag-grid.com/react-data-grid/row-dragging-customisation Configure the number of pixels a row must be dragged before the drag event starts. Set to 0 to start dragging immediately on mousedown. This example demonstrates a typical AG Grid setup with row dragging enabled. ```javascript "use client"; import React, { useCallback, useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import "./styles.css"; import { CellStyleModule, ClientSideRowModelModule, NumberFilterModule, RowDragModule, TextFilterModule, ValidationModule, } from "ag-grid-community"; import CustomCellRenderer from "./customCellRenderer.jsx"; import { useFetchJson } from "./useFetchJson"; const modules = [ TextFilterModule, NumberFilterModule, RowDragModule, CellStyleModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete", cellClass: "custom-athlete-cell", cellRenderer: CustomCellRenderer, }, { field: "country" }, { field: "year", width: 100 }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, ]); const defaultColDef = useMemo(() => { return { width: 170, filter: true, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); const onRowDragEnter = useCallback((e) => { console.log("onRowDragEnter: node", e.node.id); }, []); const onRowDragEnd = useCallback((e) => { console.log("onRowDragEnd: node", e.node.id); }, []); const onRowDragCancel = useCallback((e) => { console.log("onRowDragCancel: node", e.node.id); }, []); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### AG-Grid React Context Menu Example Source: https://www.ag-grid.com/react-data-grid/context-menu This snippet shows a complete AG-Grid React component setup that includes the ContextMenuModule. It fetches data and configures columns for display. Ensure the 'ag-grid-enterprise' package is installed for enterprise modules. ```javascript "use client"; import React, { useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { AgChartsEnterpriseModule } from "ag-charts-enterprise"; import { ClientSideRowModelModule, ValidationModule } from "ag-grid-community"; import { CellSelectionModule, ClipboardModule, ColumnMenuModule, ContextMenuModule, ExcelExportModule, IntegratedChartsModule, } from "ag-grid-enterprise"; import { useFetchJson } from "./useFetchJson"; const modules = [ ClientSideRowModelModule, ClipboardModule, ExcelExportModule, ColumnMenuModule, ContextMenuModule, CellSelectionModule, IntegratedChartsModule.with(AgChartsEnterpriseModule), ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete", minWidth: 200 }, { field: "age" }, { field: "country", minWidth: 200 }, { field: "year" }, { field: "date", minWidth: 180 }, { field: "sport", minWidth: 200 }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]); const defaultColDef = useMemo(() => { return { flex: 1, minWidth: 100, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Grid Initialization and Datasource Setup Source: https://www.ag-grid.com/react-data-grid/server-side-model-tree-data Handles the grid's 'ready' event to fetch data and set up the server-side datasource. It registers a fake server with the data and then creates and registers the datasource with the grid API. ```javascript const onGridReady = useCallback((params) => { fetch("https://www.ag-grid.com/example-assets/tree-data.json") .then((resp) => resp.json()) .then((data) => { // setup the fake server with entire dataset fakeServer = new FakeServer(data); // create datasource with a reference to the fake server const datasource = getServerSideDatasource(fakeServer); // register the datasource with the grid params.api.setGridOption("serverSideDatasource", datasource); }); }, []); ``` -------------------------------- ### AG-Grid React Component Setup Source: https://www.ag-grid.com/react-data-grid/excel-export-formulas Basic setup for an AG-Grid React application, including necessary module imports and component structure. This example demonstrates the integration of AG-Grid with React. ```javascript "use client"; import React, useCallback, useMemo, useRef, useState, StrictMode, } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import "./styles.css"; import { ClientSideRowModelModule, ValidationModule } from "ag-grid-community"; import { ColumnMenuModule, ContextMenuModule, ExcelExportModule, } from "ag-grid-enterprise"; const modules = [ ClientSideRowModelModule, ExcelExportModule, ColumnMenuModule, ContextMenuModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const GridExample = () => { const gridRef = useRef(null); const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [rowData, setRowData] = useState([ { firstName: "Mair", lastName: "Inworth", age: 23, company: "Rhyzio" }, { firstName: "Clair", lastName: "Cockland", age: 38, company: "Vitz" }, { firstName: "Sonni", lastName: "Jellings", age: 24, company: "Kimia" }, { firstName: "Kit", lastName: "Clarage", age: 27, company: "Skynoodle" }, { firstName: "Tod", lastName: "de Mendoza", age: 29, company: "Teklist" }, { firstName: "Herold", lastName: "Pelman", age: 23, company: "Divavu" }, { firstName: "Paula", lastName: "Gleave", age: 37, company: "Demimbu" }, { firstName: "Kendrick", lastName: "Clayill", age: 26, company: "Brainlounge", }, { firstName: "Korrie", lastName: "Blowing", age: 32, company: "Twitternation", }, { firstName: "Ferrell", lastName: "Towhey", age: 40, company: "Nlounge" }, { firstName: "Anders", lastName: "Negri", age: 30, company: "Flipstorm" }, { firstName: "Douglas", lastName: "Dalmon", age: 25, company: "Feedbug" }, { firstName: "Roxanna", lastName: "Schukraft", age: 26, company: "Skinte" }, { firstName: "Seumas", lastName: "Pouck", age: 34, company: "Aimbu" }, { firstName: "Launce", lastName: "Welldrake", age: 25, company: "Twinte" }, { firstName: "Siegfried", lastName: "Grady", age: 34, company: "Vimbo" }, { firstName: "Vinson", lastName: "Hyams", age: 20, company: "Tanoodle" }, { firstName: "Cayla", lastName: "Duckerin", age: 21, company: "Livepath" }, { firstName: "Luigi", lastName: "Rive", age: 25, company: "Quatz" }, { firstName: "Carolyn", lastName: "Blouet", age: 29, company: "Eamia" }, ]); const [columnDefs, setColumnDefs] = useState([ { field: "firstName" }, { field: "lastName" }, { headerName: "Full Name", valueGetter: (params) => { return `${params.data.firstName} ${params.data.lastName}`; }, }, { field: "age" }, { field: "company" }, ]); return (
); }; const rootElement = document.getElementById("root"); const root = createRoot(rootElement); root.render( ); ``` -------------------------------- ### Install Project Dependencies Source: https://www.ag-grid.com/react-data-grid/server-side-operations-nodejs Install all necessary project dependencies and build the project. ```bash yarn install ``` -------------------------------- ### AG-Grid React Example with Cell Selection Source: https://www.ag-grid.com/react-data-grid/cell-selection This example demonstrates a full AG-Grid React setup with cell selection enabled. It includes necessary module imports and data fetching. ```javascript "use client"; import React, { useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { ClientSideRowModelModule, ValidationModule } from "ag-grid-community"; import { CellSelectionModule, ClipboardModule, ColumnMenuModule, ContextMenuModule, } from "ag-grid-enterprise"; import { useFetchJson } from "./useFetchJson"; const modules = [ ClientSideRowModelModule, ClipboardModule, ColumnMenuModule, ContextMenuModule, CellSelectionModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete", minWidth: 150 }, { field: "age", maxWidth: 90 }, { field: "country", minWidth: 150 }, { field: "year", maxWidth: 90 }, { field: "date", minWidth: 150 }, { field: "sport", minWidth: 150 }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]); const defaultColDef = useMemo(() => { return { flex: 1, minWidth: 100, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/small-olympic-winners.json", ); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### AG-Grid React Row Selection Example Source: https://www.ag-grid.com/react-data-grid/theming-selections A comprehensive example demonstrating AG-Grid React setup with row selection enabled and custom theming, including setting initial selected rows. ```javascript "use client"; import React, { useCallback, useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { AllCommunityModule, themeQuartz } from "ag-grid-community"; import { useFetchJson } from "./useFetchJson"; const modules = [AllCommunityModule]; const myTheme = themeQuartz.withParams({ // bright green, 10% opacity selectedRowBackgroundColor: "rgba(0, 255, 0, 0.1)", // alternating row colors will be visible through the semi-transparent // selection background color oddRowBackgroundColor: "#8881", }); const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "athlete", minWidth: 170 }, { field: "age" }, { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]); const theme = useMemo(() => { return myTheme; }, []); const rowSelection = useMemo(() => { return { mode: "multiRow" }; }, []); const defaultColDef = useMemo(() => { return { editable: true, filter: true, }; }, []); const { data, loading } = useFetchJson( "https://www.ag-grid.com/example-assets/olympic-winners.json", ); const onFirstDataRendered = useCallback((params) => { params.api.forEachNode((node) => { if ( node.rowIndex === 2 || node.rowIndex === 3 || node.rowIndex === 4 || node.rowIndex === 5 || node.rowIndex === 6 ) { node.setSelected(true); } }); }, []); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ``` -------------------------------- ### Start the Application Source: https://www.ag-grid.com/react-data-grid/server-side-operations-nodejs Execute this command to run the Node.js server application. ```bash yarn start ``` -------------------------------- ### Master Detail with Row Grouping Example Source: https://www.ag-grid.com/react-data-grid/server-side-model-master-detail This is the main React component for the AG-Grid example. It sets up the grid with server-side data, row grouping, and master-detail functionality. Ensure 'ag-grid-enterprise' is installed and imported. ```jsx "use client"; import React, { useCallback, useMemo, useState, StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { AgGridReact, AgGridProvider } from "ag-grid-react"; import { ClientSideRowModelModule, RowApiModule, ValidationModule, } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, MasterDetailModule, RowGroupingModule, ServerSideRowModelModule, } from "ag-grid-enterprise"; import { FakeServer } from "./fakeServer"; const modules = [ RowApiModule, ClientSideRowModelModule, ColumnsToolPanelModule, MasterDetailModule, ColumnMenuModule, ContextMenuModule, RowGroupingModule, ServerSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]; const getServerSideDatasource = (server) => { return { getRows: (params) => { console.log("[Datasource] - rows requested by grid: ", params.request); const response = server.getData(params.request); // adding delay to simulate real server call setTimeout(() => { if (response.success) { // call the success callback params.success({ rowData: response.rows, rowCount: response.lastRow, }); } else { // inform the grid request failed params.fail(); } }, 200); }, }; }; const GridExample = () => { const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []); const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []); const [columnDefs, setColumnDefs] = useState([ { field: "country", rowGroup: true, hide: true }, { field: "accountId", hide: true }, { field: "name" }, { field: "calls" }, { field: "totalDuration" }, ]); const defaultColDef = useMemo(() => { return { flex: 1, }; }, []); const autoGroupColumnDef = useMemo(() => { return { field: "accountId", }; }, []); const detailCellRendererParams = useMemo(() => { return { detailGridOptions: { columnDefs: [ { field: "callId" }, { field: "direction" }, { field: "duration", valueFormatter: "x.toLocaleString() + 's'" }, { field: "switchCode" }, { field: "number" }, ], defaultColDef: { flex: 1, }, }, getDetailRowData: (params) => { // supply details records to detail cell renderer (i.e. detail grid) params.successCallback(params.data.callRecords); }, }; }, []); const onGridReady = useCallback((params) => { fetch("https://www.ag-grid.com/example-assets/call-data.json") .then((resp) => resp.json()) .then((data) => { // setup the fake server with entire dataset const fakeServer = FakeServer(data); // create datasource with a reference to the fake server const datasource = getServerSideDatasource(fakeServer); // register the datasource with the grid params.api.setGridOption("serverSideDatasource", datasource); }); setTimeout(() => { // expand some master row const someRow = params.api.getRowNode("1"); if (someRow) { someRow.setExpanded(true); } }, 1000); }, []); return (
); }; const root = createRoot(document.getElementById("root")); root.render( , ); ```