Uploading Files with React (POST Request)
Luqman Shaban
Building AI-Driven Micro-SaaS & Web Apps | Founder @ Tanelt.com | Automating & Scaling Businesses
Introduction
React applications are known for their interactivity and user-friendliness. But what if you want users to upload files, like images or document? Don't worry! In this article I'll guide you through the process of creating a React component that will handle file uploads. We'll break down the process, explore using libraries like axios, and even touch upon handling upload progress and displaying success/error messages.
Project Set Up
To get started, I've used vite to create the react app and picked typescript. Follow the guide on how to set up react using vite. After you're done setting up the project, open it in a code editor of your choice. (I'll be using VsCode). For styling, we'll be using tailwind css, here's a guide on how to set it up. Once done, Open App.tsx and replace it's content with the following:
export default function App() {
return (
<h1 className="text-3xl font-bold underline">
Hello world!
</h1>
)
}
open your terminal and run:
npm run dev
you should see something similar to this
Open the port on your browser and you should see
Creating the HTML Form
export default function App() {
return (
<div className="flex justify-center items-center pt-44">
<form>
<div className='flex flex-col gap-y-4'>
<div className="flex items-center justify-center w-full mt-5">
<label htmlFor="dropzone-file" className="flex flex-col items-center justify-center p-3 w-full h-36 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-[#ffffff] hover:bg-[#f9f9f9]">
<div className="flex flex-col items-center justify-center pt-5 pb-6">
<svg className="w-8 h-8 mb-4 text-[#7b7b7b] dark:text-[#9b9b9b]" aria-hidden="true" xmlns="https://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 16">
<path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2" />
</svg>
<p className="mb-2 text-sm text-[#7b7b7b] dark:text-[#9b9b9b]"><span className="font-semibold">Click to upload</span> or drag and drop</p>
<p className="text-xs text-[#7b7b7b] dark:text-[#9b9b9b]">pdf, docx, doc (MAX.14MB)</p>
</div>
<input id="dropzone-file" type="file" className="hidden" accept='.pdf, .docx, .doc, .odt' required />
</label>
</div>
<button className="py-3 w-full bg-[blue] text-white rounded-lg text-center">Submit</button>
</div>
</form>
</div>
)
}
The style is very minimal but it serves the purpose for now. However, you may modify the style to match your own preferences.
Adding Functionality
Up to this point you might have noticed that no message is shown after the file has uploaded. To address this challenge, we'l use React's useState hook to dynamically display a message letting the user know that the file has being successfully uploaded.
Step 1 - import useState from React.
import { useState } from "react"
Step 2 - Create a state variable
const [isFileUploaded, setIsFileUploaded] = useState(false)
Step 3 - conditionally render the message after file upload
{/* Notify the user after successful file upload */}
{isFileUploaded && <div className="flex flex-col gap-y-1 w-full">
<p className="text-center text-blue-800 text-sm">File uploaded</p>
<div className="h-1.5 w-full bg-green-500 rounded-full"></div>
</div>}
Storing the file in a state variable
To save the upload file, we'll create a state variable and method to listen for file uploads.
const [file, setFile] = useState<File | null>(null)
In the above code we declaring a state variable and assigning File or null type.
领英推荐
Create HTML event method that listens for file uploads
const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.currentTarget.files
if(files)
setFile(files[0])
// show success message on file upload
setIsFileUploaded(true)
}
This code snippet handles what happens when a user selects a file for upload.
Pass the function to onChange event in the HTML input
<input id="dropzone-file" type="file" className="hidden" accept='.pdf, .docx, .doc, .odt' required onChange={handleFileInput}/>
This code defines a hidden file input element that utilizes the handleFileInput function.
Send the file to the server
For this, we'll use axios.
npm i axios
import axios from 'axios';
const handleFileSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
const formData = new FormData()
if (file) {
formData.append('file', file)
}
try {
const response = await axios.post(`your_api_endpoint`, formData, { headers: { "Content-Type": "multipart/form-data" } })
console.log(response);
} catch (error: unknown) {
console.error(error);
}
}
This code snippet handles submitting the form with the uploaded file.
In essence, this code snippet takes the uploaded file, prepares it for sending with FormData, and uses axios.post to submit it to your server-side API.
Pass the handleFileSubmit method to the form
<form onSubmit={handleFileSubmit}>
Conclusion
By now, you've equipped yourself with the skills to confidently integrate file uploads into your React applications. Remember, this is just the beginning! You can further enhance the user experience by adding features like drag-and-drop upload zones, progress bars, and informative error messages.
Stay Connected, Keep Learning!
If you have any questions or want to delve deeper into React development, feel free to join our WhatsApp group! We have a thriving community of developers eager to share knowledge and collaborate.
Keep up-to-date with the latest React trends and techniques. Happy coding!
Building HoverConsole.com | Entrepreneur | Visionary
9 个月This is incredibly detailed and helpful! ?? Thanks for breaking down the file upload process in React so details. ? ?? Kudos for sharing such valuable insights!