Components
Loading preview...
This React component provides a robust and versatile file upload experience, enhancing user interaction with features like drag-and-drop, file validation (size and type), and clear visual feedback. It addresses the common need for controlled file uploads in web applications, ensuring a smooth and user-friendly process. The component works by utilizing React's useState and useRef hooks to manage file state, drag-and-drop interactions, and error handling. It leverages a controlled input element for file selection and employs event handlers to manage file uploads and removals. Files are validated against specified size and type constraints, providing informative error messages to the user. The component also generates unique IDs for each uploaded file, allowing for easy tracking and management. A visual representation of the selected files is displayed, including file icons, names, sizes, and a remove button for each file. Furthermore, the component supports single or multiple file uploads and provides customizable options for accepted file types, maximum file size, and component styling through props. The process begins with the user either clicking the upload area or dragging and dropping files into it. The component then validates the file(s), adding valid files to the state and displaying any errors. The user can remove files individually and the component cleanly removes preview URLs to prevent memory leaks. Use cases include e-commerce platforms (product image uploads), content management systems (document uploads), and any application requiring controlled file uploads with validation. The customizable nature of the component allows seamless integration into various applications. For example, you can restrict uploads to image files only, limit the file size to 10MB, and disable the upload functionality based on application state. Key technologies used include React's functional components, useState and useRef hooks, and useCallback for performance optimization. The component uses a custom function to format file sizes for better readability and another to determine the appropriate file icon based on file type. In addition, it provides callback functions (`onFilesSelect`, `onFilesRemove`) to allow the parent component to handle the selected or updated files. This allows for flexibility in how the uploaded files are processed and utilized. The demo showcases custom styling with color variables and dark mode support.