Open In App

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

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:

1

Article Tags :