How to Load Data from a File in Next.js?
Last Updated :
01 May, 2024
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.
JavaScript
//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:

Similar Reads
How To Fetch Data From APIs In NextJS? Fetching data from APIs in Next.js can be done using built-in methods like getServerSideProps, getStaticProps, or client-side fetching with useEffect. This flexibility supports both server-side and static data fetching.Prerequisites:NPM & NodeJSReactJSReact HooksReact RouterApproachTo fetch data
2 min read
How to load a JSON object from a file with ajax? Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications.
3 min read
How to Create a Next.js form ? Forms are an essential part of many web applications, allowing users to input data and interact with the website. Next.js, with its powerful features for building server-rendered React applications, provides an ideal platform for creating forms. In this article, we'll explore step-by-step how to cre
4 min read
How to Load NextJS Images from an External URL ? In Next.js, loading external URL images is important because it allows developers to incorporate dynamic content and enrich user experiences by displaying images from various sources seamlessly within their applications.In this article, we will explore two different approaches to loading NextJS Imag
2 min read
How to add Media Downloader in Next.js ? In this article, we are going to learn how we can add Media Downloader in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components con
2 min read