
Generate your React app with prompts or Figma
How do I add file upload in React using MUI?
Why use Axios for file upload in React?
How can I show upload progress in a React app?
What are Higher Order Components (HOCs) in React?
Looking to add a stylish file upload to your React app? Learn how Material-UI components can make uploads smooth, intuitive, and user-friendly. From drag-and-drop to progress tracking, we’ll guide you through building a polished solution.
In modern web applications, file upload is a common requirement.
Users expect smooth, responsive interfaces when sending files to a server. If you're building with React and want a polished interface, using React Material-UI components is a great approach.
But how do you integrate a file upload component that is both functional and visually appealing?
In this blog, we will cover how to implement React MUI file upload in your applications. You'll learn how to use Material UI components to create an intuitive file upload experience, handle files, and integrate with an API efficiently.
We will also discuss advanced techniques like drag-and-drop , file validation, progress tracking, and combining multiple components for a complete solution.
Before building the upload functionality, ensure your React project is set up with Material UI. Material UI provides a wide range of components, from buttons to form inputs, that help maintain a consistent design. If you haven’t installed Material UI yet, you can do so using npm or yarn.
npm install @mui/material @emotion/react @emotion/styled
Or with yarn:
yarn add @mui/material @emotion/react @emotion/styled
Next, make sure you have the necessary icons if you plan to use them for upload buttons:
npm install @mui/icons-material
These icons will make your upload buttons more visually appealing and intuitive for users. The combination of buttons, icons, and input fields ensures that your upload component feels modern and user-friendly.
Material UI makes creating a file upload component straightforward. Start by importing the required components.
import React, { useState } from 'react'; import { Button, Stack, LinearProgress } from '@mui/material'; import IconButton from '@mui/material/IconButton'; import PhotoCamera from '@mui/icons-material/PhotoCamera'; export default function UploadButtons() { const [selectedFiles, setSelectedFiles] = useState(null); const handleFileChange = (event) => { setSelectedFiles(event.target.files); }; const handleUpload = () => { // File upload logic console.log(selectedFiles); }; return ( <Stack direction="row" spacing={2} alignItems="center"> <label htmlFor="contained-button-file"> <input accept="image/*" id="contained-button-file" multiple type="file" style={{ display: 'none' }} onChange={handleFileChange} /> <Button variant="contained" component="span" color="primary"> Upload Files </Button> </label> <IconButton color="primary" aria-label="upload picture" component="span"> <PhotoCamera /> </IconButton> </Stack> ); }
Button with variant contained and component span to create a clickable area that opens the file selection dialog.IconButton provides a visual icon for uploading pictures, which improves usability.input type file is hidden and linked via label htmlFor to maintain accessibility.handleFileChange stores the selected files in the state for later processing.This simple component lays the foundation for handling file uploads in your React project using Material UI.
Many applications require uploading multiple files at once. Material UI allows for this using the multiple attribute in the input field. You can also display a progress bar for each file to give users feedback.
const [progress, setProgress] = useState(0); const uploadFiles = () => { const totalFiles = selectedFiles.length; let uploaded = 0; Array.from(selectedFiles).forEach((file) => { // Simulate upload setTimeout(() => { uploaded += 1; setProgress((uploaded / totalFiles) * 100); }, 500); }); };
Using from Material UI, you can show real-time upload progress for multiple files. Users can immediately see how far along their uploads are, which improves the experience.
This diagram illustrates the step-by-step process of file uploads: file selection, server upload, and displaying progress. It's a helpful visualization for planning your file upload feature.
To send files to the server, you can integrate with APIs using axios. Axios simplifies HTTP requests and supports progress tracking.
This integration ensures that your uploaded files reach the server efficiently while providing real-time progress feedback.
| File Name | Status | Progress |
|---|---|---|
| image1.png | Uploading | 45% |
| document.pdf | Completed | 100% |
| photo.jpg | Error | 0% |
Tracking each file's status is crucial for providing a smooth user experience. You can dynamically update this table as the upload progresses.
Material UI doesn't include a native drag-and-drop upload, but combining it with provides a seamless experience.
This approach makes uploading intuitive. Users can drag multiple files at once, which is especially useful for applications handling many images or documents.
Validating files before upload is essential. You can check type file and size to prevent invalid files from being uploaded.
This simple validation ensures that users don't upload unsupported or overly large files, reducing server errors.
By combining all the components, you can create a material ui upload form that is user-friendly and functional.
This approach gives users a complete interface with buttons, progress indicators, and optional drag-and-drop areas.
Using attributes ensures your file upload component is accessible. For instance, helps screen readers interpret buttons correctly. Accessibility is often overlooked but significantly improves user experience.
Material UI allows extensive customization. You can adjust colors, spacing, and typography to match your application's design.
This small customization makes the button more visually appealing and consistent with your application's branding.
Want to go beyond file uploads? With Rocket.new, you can turn any idea into a fully functional React app—just describe it in plain language or import your Figma design. Build, customize, and deploy without touching a single line of code.
React – Implement a file upload component using MUI — Community-driven Q&A offering hands-on code examples for integrating file upload with Material UI and .- View complete post on Stack Overflow
Creating a React MUI file upload feature is straightforward with Material UI components. By combining buttons, input fields, icons, progress bars, and optional drag-and-drop areas, you can deliver a seamless file upload experience. Integrating with APIs using axios ensures your files reach the server efficiently. With file validation and accessibility improvements, your upload feature can handle multiple scenarios while providing an intuitive interface.
LinearProgressreact-dropzonearia-labelaria-label="upload picture"IconButtonnpm install axios
import axios from 'axios';
const handleUpload = () => {
const formData = new FormData();
Array.from(selectedFiles).forEach((file) => {
formData.append('files', file);
});
axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setProgress(percentCompleted);
}
})
.then((response) => {
console.log('Files uploaded successfully', response.data);
})
.catch((error) => {
console.error('Upload failed', error);
});
};
npm install react-dropzone
import { useDropzone } from 'react-dropzone';
const DropzoneArea = () => {
const { getRootProps, getInputProps } = useDropzone({
onDrop: (acceptedFiles) => setSelectedFiles(acceptedFiles)
});
return (
<div {...getRootProps()} style={{ border: '2px dashed gray', padding: 20 }}>
<input {...getInputProps()} />
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
);
};
const handleFileChange = (event) => {
const validFiles = Array.from(event.target.files).filter(file => file.size <= 5 * 1024 * 1024);
setSelectedFiles(validFiles);
};
import Stack from '@mui/material/Stack';
import LinearProgress from '@mui/material/LinearProgress';
const UploadForm = () => (
<Stack spacing={2} direction="column">
<UploadButtons />
{progress > 0 && <LinearProgress variant="determinate" value={progress} />}
</Stack>
);
<Button variant="contained" color="primary" style={{ borderRadius: 8, padding: '10px 20px' }}>
Upload Files
</Button>