React file upload component

Cannot find good examples of a simple file upload component in react + ts which accepts multiple file types like .pdf, .csv, .docx, etc. Any suggestions?
4 Replies
Unknown User
Unknown Userβ€’2y ago
Message Not Public
Sign In & Join Server To View
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Untested code, but it should be pretty simple to code one yourself:
import React, { useState } from "react";

interface FileUploadProps {
onUpload: (files: FileList) => void;
accept: string;
}

const FileUpload: React.FC<FileUploadProps> = ({ onUpload, accept }) => {
const [selectedFiles, setSelectedFiles] = useState<FileList | null>(null);

const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
setSelectedFiles(files);
onUpload(files);
};

return (
<div>
<input
type="file"
accept={accept}
multiple
onChange={handleFileSelect}
/>
{selectedFiles && (
<div>
<ul>
{Array.from(selectedFiles).map((file, index) => (
<li key={index}>{file.name}</li>
))}
</ul>
</div>
)}
</div>
);
};

export default FileUpload;
import React, { useState } from "react";

interface FileUploadProps {
onUpload: (files: FileList) => void;
accept: string;
}

const FileUpload: React.FC<FileUploadProps> = ({ onUpload, accept }) => {
const [selectedFiles, setSelectedFiles] = useState<FileList | null>(null);

const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
setSelectedFiles(files);
onUpload(files);
};

return (
<div>
<input
type="file"
accept={accept}
multiple
onChange={handleFileSelect}
/>
{selectedFiles && (
<div>
<ul>
{Array.from(selectedFiles).map((file, index) => (
<li key={index}>{file.name}</li>
))}
</ul>
</div>
)}
</div>
);
};

export default FileUpload;
You can pass in accept props to define what file types to accept, like accept=".pdf,.csv,.docx"
Jaaneek
Jaaneekβ€’2y ago
I always go with https://www.npmjs.com/package/use-file-picker Btw im biased since I’m the author
npm
use-file-picker
Simple react hook to open browser file selector.. Latest version: 1.5.2, last published: 2 months ago. Start using use-file-picker in your project by running npm i use-file-picker. There are 3 other projects in the npm registry using use-file-picker.
Want results from more Discord servers?
Add your server