How to Use a Simple Form Submit with Files in React (2024)

Introduction

Uploading images or files is a major function of any app. It is an essential requirement for creating a truly full-stack app. For example, Facebook, Instagram, and Snapchat all have the functionality to upload images and videos.

In traditional HTML sites, the file upload form forces a page refresh, which might be confusing to users. Also, you might want to customize the look of the file input in the form to make it resonate with your overall app design. When it comes to both of these issues, React can help you provide a better user experience.

This guide will get you up and running with file uploads in React.

Creating a Basic Form

In your App.js file, create a basic form that with a name field and a file input.

Now, add state in the component to store the name and the file data.

 import React, { useState } from "react";const App = () => { const [name, setName] = useState(""); const [selectedFile, setSelectedFile] = useState(null); return ( <div className="App"> <form> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <input type="file" value={selectedFile} onChange={(e) => setSelectedFile(e.target.files[0])} /> </form> </div> );}; 

Creating a Custom File Uploader Component

Now that the basic form is set up, create a custom file uploader component that can be reused across multiple forms in the app.

If you check the output of the current form, you will notice that the file input doesn't have a great look; that's because the browser defines its default styling. In this section, you will learn how to create a file upload component with custom styling.

 const FileUploader = () => { const handleFileInput = () => {} return ( <div className="file-uploader"> <input type="file" onChange={handleFileInput}> </div> )} 

To create a custom file uploader, the first step is to hide the default input and trigger the change event using a ref.

 import React, {useRef} from 'react'const FileUploader = ({onFileSelect}) => { const fileInput = useRef(null) const handleFileInput = (e) => { // handle validations onFileSelect(e.target.files[0]) } return ( <div className="file-uploader"> <input type="file" onChange={handleFileInput}> <button onClick={e => fileInput.current && fileInput.current.click()} className="btn btn-primary"> </div> )} 

You can style the upload button to match the theme of your overall application. Send the uploaded file back to the parent component using a callback prop; in this case, it is onFileSelect. Inside the handleFileInput method, you can do validations like checking for filesize, file extensions, etc., and based on that, send feedback to the parent component using callback props like onFileSelectSuccess and onFileSelectError.

 const handleFileInput = (e) => { // handle validations const file = e.target.files[0]; if (file.size > 1024) onFileSelectError({ error: "File size cannot exceed more than 1MB" }); else onFileSelectSuccess(file);}; 

Adding the File Uploader Component to the Form

Add the file uploader component as follows :

 import React, { useState } from "react";const App = () => { const [name, setName] = useState(""); const [selectedFile, setSelectedFile] = useState(null); const submitForm = () => {}; return ( <div className="App"> <form> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <FileUploaded onFileSelectSuccess={(file) => setSelectedFile(file)} onFileSelectError={({ error }) => alert(error)} /> <button onClick={submitForm}>Submit</button> </form> </div> );}; 

Uploading Files Using FormData

Upload a selected file using the FormData object. Append the name and file using the append method of the formData object.

 const submitForm = () => { const formData = new FormData(); formData.append("name", name); formData.append("file", selectedFile); axios .post(UPLOAD_URL, formData) .then((res) => { alert("File Upload success"); }) .catch((err) => alert("File Upload Error"));}; 

That's pretty much it. You have successfully created and added a custom file upload component.

Conclusion

File uploading is an essential part of any web app. You can use other third-party libraries to create custom file upload inputs, but you should have a fair idea of how they are implemented under the hood.

There are several instances where file uploads are required, but with some customization. Third-party libraries may not always help you out in such cases, however, your custom file upload utility can.

Learn More

Explore these React courses from Pluralsight to continue learning:

  • React Course
  • Building React Apps
  • Calling APIs With React
  • React Best Practices
How to Use a Simple Form Submit with Files in React (2024)
Top Articles
Understanding Pension Choices: Lump Sum vs. Annuity Options
Investing for Kids: A Parent’s Guide for Your Child’s Long-Term Financial Success
Kostner Wingback Bed
417-990-0201
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Brady Hughes Justified
Identifont Upload
Practical Magic 123Movies
Ashlyn Peaks Bio
27 Places With The Absolute Best Pizza In NYC
Flat Twist Near Me
2024 Non-Homestead Millage - Clarkston Community Schools
Wizard Build Season 28
065106619
Craigslist Red Wing Mn
Osborn-Checkliste: Ideen finden mit System
Mychart Anmed Health Login
Craigslist Pet Phoenix
Never Give Up Quotes to Keep You Going
Brazos Valley Busted Newspaper
Www.dunkinbaskinrunsonyou.con
Galaxy Fold 4 im Test: Kauftipp trotz Nachfolger?
Boxer Puppies For Sale In Amish Country Ohio
Sorrento Gourmet Pizza Goshen Photos
The Eight of Cups Tarot Card Meaning - The Ultimate Guide
Villano Antillano Desnuda
Play It Again Sports Forsyth Photos
Isablove
Dairy Queen Lobby Hours
+18886727547
Mrstryst
Fridley Tsa Precheck
2012 Street Glide Blue Book Value
Seymour Johnson AFB | MilitaryINSTALLATIONS
A Man Called Otto Showtimes Near Amc Muncie 12
Aliciabibs
Ise-Vm-K9 Eol
Directions To Advance Auto
sacramento for sale by owner "boats" - craigslist
The Angel Next Door Spoils Me Rotten Gogoanime
Www.craigslist.com Waco
Kutty Movie Net
Rocky Bfb Asset
Ehome America Coupon Code
Enr 2100
Okta Login Nordstrom
Spn 3464 Engine Throttle Actuator 1 Control Command
18443168434
Game Akin To Bingo Nyt
Ics 400 Test Answers 2022
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6266

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.