Stars
How to Implement MUI File Upload in React Using Vite and Axios: A Comprehensive Guide
calendar26 Oct 2024
read11 minute read

How to Implement MUI File Upload in React Using Vite and Axios: A Comprehensive Guide

Introduction

In modern web applications, file uploads play a vital role, enabling users to upload documents, images, and more, directly to a server. Implementing efficient file upload functionality can significantly enhance the user experience. In this blog, we'll explore how to create a sleek mui file upload feature using React and Material UI (MUI). React is a powerful JavaScript library for building user interfaces, while MUI is a collection of customizable React components based on Google's Material Design. We'll leverage Vite, a modern build tool, for faster development compared to traditional bundlers like Webpack. This step-by-step guide will walk you through creating a reliable file upload feature, focusing on performance and user experience.

Setting Up the React Project with Vite

To get started with the mui file upload project, we'll set up a React environment using Vite. If you need a more in-depth guide, check out our detailed Beginners Guide to Using Vite with React. Below are the essential steps to get you up and running:

  1. First, create a new React project using Vite by running the following command:
    npm create vite@latest mui-file-upload
    
  2. Navigate to the project directory:
    cd mui-file-upload
    
  3. Install project dependencies:
    npm install
    
  4. Next, add MUI and Axios to your project:
    npm install @mui/material axios
    

Vite offers blazing-fast build times, hot module replacement, and a simpler configuration than Webpack. These benefits make it an excellent choice when building performance-sensitive features like a mui file upload. Now, let's dive into creating the file upload functionality!

Creating the File Upload Button with MUI

To start building our mui file upload feature, we'll create a simple and user-friendly upload button using Material UI (MUI). The Button component from MUI is versatile and easy to style, making it perfect for creating an intuitive file upload button.

First, let's import the Button component and set up a basic button for file uploads:

import React from 'react';
import Button from '@mui/material/Button';

export default function UploadButton() {
  return (
    <Button variant="contained" color="primary" component="label">
      Upload File
      <input type="file" hidden />
    </Button>
  );
}

Here, the Button component uses the variant="contained" prop for a filled style, and the color="primary" prop to match your theme's primary color. The component="label" prop makes the button a label for the hidden <input> element, triggering file selection when clicked.

To make your button stand out, you can customize it using MUI’s powerful theming capabilities. MUI allows you to adjust the button’s color, size, and even add icons. Here's an example of a more customized button:

<Button
  variant="contained"
  color="secondary"
  startIcon={<CloudUploadIcon />}
  sx={{ margin: 2, padding: '10px 20px' }}
>
  Upload
</Button>

This example uses startIcon to add an icon at the beginning of the button, and the sx prop for inline styling. The ability to quickly change button styles makes MUI an ideal choice for creating visually appealing mui file upload components.

4. Building the File Upload Form

Now, let's create a form component for our mui file upload feature using MUI’s TextField. The TextField component can be customized to handle various input types, but in this case, we’ll focus on file uploads.

Here’s a basic form setup with a file input field:

import React from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';

export default function UploadForm() {
  return (
    <form>
      <TextField
        type="file"
        variant="outlined"
        inputProps={{ accept: 'image/*' }}
        fullWidth
        margin="normal"
      />
      <Button variant="contained" color="primary" type="submit">
        Upload
      </Button>
    </form>
  );
}

and after some styles it will look like this 


Using the type="file" attribute is crucial for file uploads, ensuring that the user can select files from their local system. You can add validation through attributes like accept, which limits file types (e.g., accept="image/*" allows only image files). This attention to detail improves the user experience by preventing invalid file types from being selected. The full-width TextField with proper margin also makes the form more accessible and visually appealing for the mui file upload functionality.

Handling File Upload with Axios

Uploading files efficiently is a crucial task in modern web applications, and using Axios makes this process both straightforward and manageable. In our mui file upload example, Axios takes center stage, handling the file transfer seamlessly while keeping our React app responsive.

The heart of our upload process lies in a function that triggers when the user submits the form. We use a FormData object, a native JavaScript tool, that’s perfect for handling multipart data like files. The setup is simple: the selected file is wrapped in FormData and passed to Axios, which then takes care of sending it to the server.

const handleFileUpload = async (event) => {
  event.preventDefault(); 
  setUploadProgress(0); 
  setUploadComplete(false); 

  const formData = new FormData();
  const file = event.target.elements.fileInput.files[0]; 
  formData.append('file', file);

  try {
    await axios.post('https://api.escuelajs.co/api/v1/files/upload', formData, {
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        setUploadProgress(percentCompleted);
      },
    });
    setUploadComplete(true); 
  } catch (error) {
    console.error('Error uploading file:', error);
  }
};

The logic here is clean and straightforward. We handle the file selection through an <input> element, pass it to FormData, and let Axios do the heavy lifting. By leveraging onUploadProgress, we can keep users updated on the progress—an essential feature that makes the upload experience engaging rather than frustrating.

Beyond the mechanics, it’s wise to validate files on the client side before sending them off, ensuring that our server isn't burdened with invalid requests. Additionally, keeping the upload secure over HTTPS adds a layer of protection for sensitive data, making the mui file upload process both reliable and safe.

Implementing Progress Feedback Using MUI

Feedback during a file upload can be the difference between a confident user and a confused one. That's where MUI’s flexibility shines, allowing us to seamlessly integrate progress indicators that keep users in the loop.

Using Axios’s onUploadProgress feature, we can dynamically update the state with the current progress percentage. MUI’s Typography component provides a straightforward yet elegant way to display this feedback, without cluttering the UI.

{uploadProgress > 0 && (
  <Typography variant="body2" color="textSecondary">
    Upload Progress: {uploadProgress}%
  </Typography>
)}

This component elegantly fades in once the upload starts, clearly displaying the percentage completed. It’s a small touch but adds a professional feel to the user experience. Similarly, when the upload completes, a confirmation message appears—celebrating a job well done:

{uploadComplete && (
  <Typography variant="body2" color="success.main" sx={{ display: 'flex', alignItems: 'center' }}>
    Upload Complete <CheckCircleOutlineOutlined sx={{ ml: 1 }} />
  </Typography>
)}

This combination of progress feedback and visual confirmation ensures that users are never left guessing. The dynamic update of the upload progress keeps the interaction engaging, while the success message provides closure. It’s about creating a seamless journey—from file selection to completion—where users feel in control at every step. That's the beauty of building a robust mui file upload feature with modern tools like Axios and MUI.

Error Handling and User Feedback

Handling errors during a file upload is crucial for a smooth user experience. Common issues include network disruptions, server errors, and uploading unsupported file types. React’s state management combined with Axios’s error handling makes it straightforward to manage these problems gracefully.

In our mui file upload example, error feedback is handled using MUI's Typography component. If an upload fails, we display a user-friendly error message.

const handleFileUpload = async (event) => {
  event.preventDefault();
  setUploadProgress(0); 
  setUploadComplete(false);
  setUploadError(null); 

  const formData = new FormData();
  const file = event.target.elements.fileInput.files[0];
  formData.append('file', file);

  try {
    await axios.post('https://api.escuelajs.co/api/v1/files/upload', formData, {
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        setUploadProgress(percentCompleted);
      },
    });
    setUploadComplete(true);
  } catch (error) {
    console.error('Error uploading file:', error);
    setUploadError('Failed to upload file. Please try again.');
  }
};

Errors are displayed dynamically using:

{uploadError && (
  <Typography variant="body2" color="error" sx={{ display: 'flex', alignItems: 'center' }}>
    {uploadError} <ErrorOutlineOutlined sx={{ ml: 1 }} />
  </Typography>
)}

This ensures users are kept informed of any issues, enhancing the mui file upload experience with clear, actionable feedback.

Enhancing Reusability with Custom Hooks

Custom hooks in React are a fantastic way to streamline your code and manage reusable logic. In the context of our mui file upload functionality, we can create a custom hook to encapsulate the file upload process, including error handling, progress updates, and completion status.

Here’s a custom hook that manages the core upload logic:

import { useState } from 'react';
import axios from 'axios';

const useFileUpload = () => {
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadComplete, setUploadComplete] = useState(false);
  const [uploadError, setUploadError] = useState(null);

  const uploadFile = async (file) => {
    setUploadProgress(0);
    setUploadComplete(false);
    setUploadError(null);

    const formData = new FormData();
    formData.append('file', file);

    try {
      await axios.post('https://api.escuelajs.co/api/v1/files/upload', formData, {
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setUploadProgress(percentCompleted);
        },
      });
      setUploadComplete(true);
    } catch (error) {
      console.error('Error uploading file:', error);
      setUploadError('Failed to upload file. Please try again.');
    }
  };

  return { uploadProgress, uploadComplete, uploadError, uploadFile };
};

By using useFileUpload, you can simplify any component that handles file uploads, ensuring consistent behavior across your application. This makes the mui file upload logic more readable, maintainable, and reusable.

Creating a Higher-Order Component (HOC) for File Upload

In React, a Higher-Order Component (HOC) is a pattern that allows you to reuse component logic. An HOC is essentially a function that takes a component as an argument and returns a new component with additional features. For our mui file upload, creating an HOC allows us to abstract the file upload logic and apply it across different components effortlessly.

Here's how we can create an HOC to handle file uploads:

import React from 'react';
import useFileUpload from './useFileUpload'; // Custom hook for file upload

// Higher-Order Component for file upload
const withFileUpload = (WrappedComponent) => {
  return function (props) {
    const { uploadProgress, uploadComplete, uploadError, uploadFile } = useFileUpload();

    const handleFileChange = (event) => {
      const file = event.target.files[0];
      if (file) uploadFile(file);
    };

    return (
      <WrappedComponent
        {...props}
        uploadProgress={uploadProgress}
        uploadComplete={uploadComplete}
        uploadError={uploadError}
        onFileChange={handleFileChange}
      />
    );
  };
};

export default withFileUpload;

This HOC wraps any component, adding upload logic to it. For example:

import React from 'react';
import withFileUpload from './withFileUpload';

function UploadInput({ onFileChange, uploadProgress, uploadComplete, uploadError }) {
  return (
    <div>
      <input type="file" onChange={onFileChange} />
      {uploadProgress > 0 && <p>Progress: {uploadProgress}%</p>}
      {uploadComplete && <p>Upload Complete!</p>}
      {uploadError && <p>Error: {uploadError}</p>}
    </div>
  );
}

export default withFileUpload(UploadInput);

By using this pattern, our file upload logic is modular, reusable, and easy to maintain. It enables consistent behavior across components, minimizing duplication and making the codebase cleaner.

Conclusion

Throughout this blog, we've explored how to implement a powerful mui file upload feature using React, MUI, Vite, and Axios. We started by setting up the project, creating customizable file upload components, and adding robust error handling and progress feedback. Custom hooks and HOCs have demonstrated how to make the code modular, reusable, and easier to manage.

Using Vite, we benefited from faster builds and simplified configuration. MUI’s components provided a polished UI, while Axios’s simplicity made file handling straightforward. For the complete code, you can explore the GitHub repository where all examples are available, allowing you to experiment and extend the functionality further. Dive in, and feel free to adapt the concepts for your own projects!

https://dev.to/codeparrot/how-to-implement-mui-file-upload-in-react-using-vite-and-axios-a-comprehensive-guide-35o4

Code Icon
Fasttrack Frontend
Development using CodeParrot AI
Background
CodeParrot Logo

CodeParrot

Ship stunning UI Lightning Fast

Y Combinator

Resources