Export Table Data to CSV in React JS | React CRUD Tutorial with Node
In this tutorial, we will learn how to export table data to a CSV file in a React JS app. We will also create a basic CRUD application using React and Node.js.
Setting up the project
First, we need to set up our project by creating a new React app. We can do this using the create-react-app command:
npx create-react-app react-crud
Creating a table component
Next, we will create a table component to display our data. We can use the following code as a starting point:
import React from 'react';
const Table = ({ data }) => {
return (
ID
Name
Age
{data.map((item, index) => (
{item.id}
{item.name}
{item.age}
))}
);
};
export default Table;
Exporting table data to CSV
To export our table data to a CSV file, we can create a function that takes our data and converts it into CSV format. We can then add a button to our table component that triggers this function when clicked. Here’s an example of how we can achieve this:
import React from 'react';
const Table = ({ data }) => {
const exportToCsv = () => {
const csvData = 'ID,Name,Agen';
data.forEach(item => {
csvData += `${item.id},${item.name},${item.age}n`;
});
const blob = new Blob([csvData], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'data.csv');
link.click();
};
return (
{/* Table content */}
);
};
export default Table;
Creating a CRUD app with Node.js
Finally, we can create a basic CRUD app using Node.js as our server. We can use Express to set up our server and create endpoints for handling CRUD operations. Here’s an example of how we can set up a simple server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/api/data', (req, res) => {
// Get data from database
res.json(data);
});
app.post('/api/data', (req, res) => {
// Create new data entry
// Save to database
res.json({ message: 'Data created successfully' });
});
app.put('/api/data/:id', (req, res) => {
// Update data entry
// Update database
res.json({ message: 'Data updated successfully' });
});
app.delete('/api/data/:id', (req, res) => {
// Delete data entry
// Delete from database
res.json({ message: 'Data deleted successfully' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
With these steps, we have successfully created a React app that can export table data to a CSV file and a Node.js server to handle CRUD operations. We now have a basic CRUD application with the ability to export data to a CSV file.
Hi sir can u make a vedio excel export data in react js