React Js Display CSV Data in Table

React Js Display CSV Data in Table:In React.js, displaying CSV data in a table involves reading the CSV file and rendering its content in a tabular format. First, you'd import a CSV and use it to read the CSV file. Next, parse the CSV data into an array of objects. Then, map through this data array, creating table rows and cells in React components. Utilize the map function to iterate over the data, generating rows and cells dynamically. Each object in the data array represents a row, and its properties correspond to table columns. Render these components within a table structure, effectively displaying the CSV data in a readable table format in a React application.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
How can I display CSV data in a table using Reactjs?
This React.js code snippet creates a simple CSV file uploader and displays its content in a table. The component uses the useState hook to manage the CSV data. When a user uploads a CSV file, the "handleFileUpload" function reads and parses the data. The component renders an input field for file uploads and a table to display the CSV content. The first row of the CSV is treated as the header, and subsequent rows are displayed as data rows in the table.
React Js Display CSV Data in Table Example
Copied to Clipboard
60
<script type="text/babel">
const { useState } = React;
function App() {
const [csvData, setCSVData] = useState([]);
const handleFileUpload = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const contents = e.target.result;
const rows = contents.split('\n');
const data = [];
for (let i = 0; i < rows.length; i++) {
const cells = rows[i].split(',');
data.push(cells);
}
setCSVData(data);
};
reader.readAsText(file);
};
return (
<div className='container'>
<h3>React Js Display CSV Data in Table </h3>
<input type="file" accept=".csv" onChange={handleFileUpload} className="file-input" />
<table className="csv-table">
<thead>
<tr className="csv-table-header">
{csvData.length > 0 &&
csvData[0].map((cell, index) => (
<th key={index} className="csv-table-header-cell">
{cell}
</th>
))}
</tr>
</thead>
<tbody>
{csvData.length > 1 &&
csvData.slice(1).map((row, rowIndex) => (
<tr key={rowIndex} className="csv-table-row">
{row.map((cell, cellIndex) => (
<td key={cellIndex} className="csv-table-cell">
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Js Display CSV Data in Table
Ad