As the field of web development continues to grow daily, we see web developers creating third-party packages/libraries. This helps them write functional codes in a lesser amount of time and more efficiently, thereby improving their website’s performance and visual appearance. 

One trend in the web development world today is the introduction of new features which are being implemented and adopted for a better user experience on websites and web applications. One such development is the evolution of the file uploading functionality, web developers have evolved from using the old and primitive method of handling file upload to a more efficient, advanced, secured and easy-to-use method.

In this article, we’ll look at:

  • What a React Component is?
  • Why do we need a React File Upload component?
  • What a File Uploader should contain
  • How to integrate a React File Upload component

What is a React Component?

React is a library for creating user interfaces that are modular. It promotes the development of reusable user interface (UI) elements that show dynamic data. By dividing user interfaces into components, React takes a different approach to building them.

Components are separate, reusable pieces of code. While working independently and returning HTML, they accomplish the same task as JavaScript functions.

Class and function components are the two types of components; in this article, we’ll base our code snippets on function components.

Class components

class MyComponent extends React.Component {
render(){
return <h1>Welcome Message!</h1>;
}
}

Function components

const MyComponent=()=> {
    return <h1>Welcome Message!</h1>;
}

Why do we need a React File Upload component?

One of the most quickly expanding features of contemporary web applications and websites is file uploading. A user might be asked to upload either a resume for a job application portal or a photo to be used as their profile picture on almost every social media website on the internet. Some even demand the paperwork that will be needed for KYC verification at institutions like banks and insurance firms.

For a web developer using the React library to build a file upload component, he/she has to take a lot into consideration when building a component that accepts the input of a file from a user. Some of these criteria are listed below.

What a file uploader should contain

  1. Friendly User Interface

Whenever a user explores a website that allows them to freely navigate through with little or no guidance, they tend to spend more time using that website. Compare that to a website where they have to watch tutorials before they could carry out an operation on it. Every user wants an all-in-one answer to their questions. Thankfully, there are ready-to-use React file upload solutions  that make uploading a file from any source painless and intuitive.

  1. Different sources of file upload

A perfect website should allow users to upload files from multiple sources aside from their devices. With the increasing popularity of cloud storage technology, most people today store their files on different cloud-based storage platforms such as Dropbox, iCloud or Google Drive.

The most advanced file upload solutions let you connect to content directly from the sources where your users have it – without the hassle or effort often required. They also maintain dozens of integrations with popular services, requiring no integration work on your part.

  1. Secure file uploads

One of the most important parts of a website is security. Files uploaded by users should be securely saved to the storage bucket to avoid theft of user-sensitive data which can be used to carry out fraudulent activities on the internet. 

One major way of securing file uploads includes the use of multiple anti-malware tools. These can scan uploaded files, make a whitelist of allowed file types, and set the minimum and maximum size of the file to be uploaded.

File upload solutions come with secure file uploading, greatly reducing your security worries over uploaded files. 

  1. Image Editing Within the Browser

Users might need to preview and edit uploaded images to align with the required size of the website or app or to make them look better. Well-designed file uploaders should support these kinds of manipulations inside the browser: crop, resize, rotate, and so on. By adding such an uploader, users can ensure that the images they upload to your website will appear as intended

Integrating a React File Upload Component

In this article, I will be discussing how you can easily include a file upload component in your React project.

We can integrate this file uploading feature in two ways: either by building the file uploader from scratch Or by using already made libraries. Both methods are viable and would depend on the needs of the client.

Whenever you consider developing software from scratch, you need to estimate the time investment as well as procedure and running costs. Keeping in mind all those essential features of file uploading—storage, UI & UX, security, and compliance—on several occasions, there’s no sense in investing in developing everything from scratch.

One undeniable logical motivation to go this way is the restricted nature of some systems, in which they can’t outsource file uploading to a third party.

In this article, we are going to integrate a custom-built file upload solution into our React.js app.

Building a Custom File Uploader in ReactJS

Uploading images is a two-step process:

  • Selecting a file
  • Sending it to a server

Building our Frontend

The first step is to create a simple React app, which you can do just by running the command below in your terminal.

npx create-react-app reactUploader

Before we start writing our code, let’s clean up our App.js file.

After that, copy and paste the following code inside your App.js file, and I’ll explain what every line does.

import React, {useState} from 'react'

const App = () => {
const [file, setFile] =useState()
const fileChangedHandler = event => {
  setFile(event.target.files[0])
}

const uploadHandler = () => {
  console.log(file)
}

  return (
	<div>
   	 <input type="file" onChange={fileChangedHandler} />
       <button onClick={uploadHandler}>Upload</button>
	</div>
  )
}

export default App

On the first line we have our import statement, to upload a file, we should store it in our state variable so that we can later send this uploaded file to our server for storage.

Before we can upload a file, we need to be able to select the file, so in our JSX, to allow the user to pick a file, we have to add <input type="file"> to our component JSX code. We also have to listen for any changes to that file. That is, we create a change handler that will trigger whenever the user picks a new file and also pass in the value of that selected file.

We now have two handler methods, one to handle our file change and another to handle our file upload to the server.

Uploading our file to the server

With our file stored in the state variable, we can send it to a server.

We can either send the file as binary data or wrapped in a FormData object—depending on what your application expects. We can send this using a package called Axios or our in-built function fetch() 

Send as binary data

uploadHandler = () => {
  axios.post('my-domain.com/file-upload', file)
}

Send as FormData

uploadHandler = () => {
  const formData = new FormData()
  formData.append(
    'myFile',
    file,
    file.name
  )
  axios.post('my-domain.com/file-upload', formData)
}

In our POST request, we send a new, empty formData object that is created by the new FormData() method. Our POST request presumes our backend server has an API endpoint at http://mydomain.com/file-upload.

Now in both cases, we can also show the user the progress of the file uploading process, you want To do that we can add the following lines of code.

uploadHandler = () => {
  ...
  axios.post('my-domain.com/file-upload', formData, {
    onUploadProgress: progressEvent => {
      console.log(progressEvent.loaded / progressEvent.total)
    }
  })
}

Conclusion

In this article, we have explained why adding a file upload component to your React website will benefit you. It allows your users to share their content with others and enjoy your site better. We have also discussed some qualities of the ideal React file upload solution. It should provide an intuitive way for users to upload files, different sources to upload from, added security, in-browser image editing, and more. 

Furthermore, we went through how you can integrate such a file upload component by making your own solution. Building your own from scratch may be good if you have plenty of time, and you only need a simple file uploader. However, if you want to deploy in the fastest way possible while having every important feature and more, then a third-party React file upload solution would be perfect.