How to Load Data from a File in Next.js?
Loading Data from files consists of using client-side techniques to read and process files in a Next.js application.
In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format.
Approach
- The FileReader API is used to read the contents of the uploaded file.
- The uploaded file is validated to ensure it is a CSV file before processing.
- The CSV data is parsed and displayed in a tabular format once the file is successfully processed.
- The useState hook is used to manage state variables for storing CSV data, error messages, and loading status.
- The handleFileUpload() function is triggered when a file is selected by the user for upload.
- Error messages are displayed if the user uploads a file that is not in CSV format or if no file is selected.
- The CSV data is split into rows and cells, then rendered in a tabular format using HTML <table> and <td> elements.
Steps to Create the Next.js Application
Step 1: Set up React Project using the Command:
npx create-next-app url-domain
Step 2: Navigate to the Project folder using:
cd url-domain
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.1"
}
Example: The below example demonstrates the Loading Data from a File in Next.JS.
//page.js
"use client";
import React, { useState } from 'react';
const Page = () => {
const [csvData, setCsvData] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleFileUpload = (event) => {
const file = event.target.files[0];
if (!file) {
setErrorMessage('Please select a file.');
return;
}
if (!file.name.endsWith('.csv')) {
setErrorMessage('Please upload a CSV file.');
return;
}
setIsLoading(true);
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target.result;
const rows = text.split('\n').map((row) => row.split(','));
setCsvData(rows);
setErrorMessage('');
setIsLoading(false);
};
reader.readAsText(file);
};
return (
<div style={{ padding:'20px', maxWidth:'800px', margin:'0 auto' }}>
<h1 style={{marginBottom: '20px' }}>
Loading Data from File
</h1>
<input type="file" onChange={handleFileUpload}
accept=".csv" style={{ marginBottom: '10px' }}
/>
{ errorMessage && <div style={{color:'red', marginBottom:'10px' }}>
{ errorMessage }</div>
}
{ isLoading ?
(
<div style={{ textAlign:'center', marginTop:'20px' }}>
Loading...
</div>
) :
(
csvData.length > 0 && (
<table style={{ borderCollapse:'collapse',
width:'100%', marginTop:'20px' }}>
<tbody>
{ csvData.map((row, index) => (
<tr key={index}>
{ row.map((cell, cellIndex) => (
<td key={cellIndex}
style={{ border:'1px solid #ccc', padding:'8px' }}>
{cell}
</td>
))}
</tr>
))
}
</tbody>
</table>
)
)
}
</div>
);
};
export default Page;
Step to run the application: Now run the application with the below command:
npm run dev
Output: