How to export our DataGrid as CSV in ReactJS ?
GridToolbarExport Component allows the user to export the displayed data to CSV with an extra API call. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to export our DataGrid as CSV in ReactJS.
Approach: Follow these simple steps in order to export our DataGrid as CSV in ReactJS. We have used the GridToolbarExport Component from the data-grid module which provides the functionality of allowing users to download the data of DataGrid in the CSV format. We have to wrap this component around its container called GridToolbarContainer. And then, we have passed these values to the main DataGrid Component using the components attribute as shown in the below example.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/data-grid
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: