Open In App

How To Create React Multiple File Upload Using NextJS And Typescript?

Last Updated : 30 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we'll explore how to implement a file upload feature in a Next.js application using React. We'll leverage the react-dropzone library to create a user-friendly interface for uploading multiple files. Additionally, we'll integrate TypeScript for type safety and ESLint for code linting to maintain code quality.

Prerequisites

Approach

Create a React multiple file upload component in a Next.js and TypeScript project by using the react-dropzone library. This component will handle file selection and provide a user-friendly interface for uploading multiple files.

Steps to create Next.js project with TypeScript

npx create-next-app@latest your-project-name --typescript --eslint

make sure you have installed react-dropzone in your project.

npm install react-dropzone

Updated dependencies in package.json file:

 "dependencies": {
"next": "14.2.3",
"react": "^18",
"react-dom": "^18",
"react-dropzone": "^14.2.3"
},

Project Structure:

Screenshot-2024-06-12-233130

Example: This example demostrates creating multiple file upload in next js with typescript.

JavaScript
// src/components/FileUpload.tsx

import React, { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';

interface FileUploadProps {
  onFilesUploaded: (files: File[]) => void;
}

const FileUpload: React.FC<FileUploadProps> = ({ onFilesUploaded }) => {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      setSelectedFiles(acceptedFiles);
      onFilesUploaded(acceptedFiles);
    },
    [onFilesUploaded]
  );

  const { getRootProps, getInputProps } = useDropzone({ onDrop });

  return (
    <div>
      <div {...getRootProps()} style={{ border: '1px dashed #ccc', padding: '20px', textAlign: 'center', marginBottom: '20px' }}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <div>
        {selectedFiles.length > 0 && (
          <ul>
            {selectedFiles.map((file, index) => (
              <li key={index}>
                {file.name} - {file.size} bytes
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
};

export default FileUpload;
JavaScript JavaScript

Start the development server

npm run dev

Output:


Next Article

Similar Reads

three90RightbarBannerImg