Get datasource from React AG Grid
In this article, we’ll show you how to get datasource from React AG Grid. This will be used for the both client side and server side pagination.
Refer to the following article to implement pagination
Here, we will add button to get the whole datasource from the AG Grid on button click event.
Demo Application
Package Version
Steps to get datasource using Grid API
1. Add AG Grid in React component
Let’s create a react application using the create-react-app
and implement AG Grid in React. Check the following article for more information.
How to implement AG Grid in React
2. Get the Grid API
In the next step, we need to fetch the Grid API to perform the action. Refer to the following article to get the Grid API & Column API.
How to get Grid API and Column API in AG Grid
3. Render the button to get the datasource
Here, we’ll read the each node of the gridApi
and collect the data. Look at the following simple code to get the datasource.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | function App() { const [gridApi, setGridApi] = useState(null); const onGridReady = (e) => { setGridApi(e.api); } const handleBtnAction = () => { const data = []; gridApi.forEachNode(node => node.data && data.push(node.data)); console.log("Grid datasource:", data); } // ... // ... return ( <div classname="App"> <h2>Get datasource from React AG Grid - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h2> <button classname="btn-action" onclick={handleBtnAction}>Get datasource</button> <div classname="ag-theme-alpine ag-style"> <AgGridReact ... ... pagination={true} paginationPageSize={5} onGridReady={onGridReady}> ... ... </AgGridReact> </div> </div> ); } export default App; |
You can check the result in the console window when you click the button.
4. Output
Run the React application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂