Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
preventDefault() method not preventing page reload ReactJS

I am trying to upload files using multer or formidable. The files are uploaded properly and also stored in the public folder. I used create-react-app to start with React project.

The problem arises when I click on the submit button to upload the data. I used the fetch API for making the POST request. The page reloads after I click on the submit button, and anything I log on the console is refreshed as well. This was also answered here, but I want to know how do I prevent my page from reloading? Should I store my images outside the public folder?

Here is my handleSubmit() function that calls when form is submitted:-

const handleSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append("poster", document.getElementById('file').files[0]);
    let res = await fetch("http://localhost:5000/api/post/exhibition", {
       method: "POST",
       body: formData
    })
    const json = await res.json()
    console.log(json)
 }

EDIT:- Handling onSubmit

<form onSubmit={handleSubmit} encType="multipart/form-data">
....
</form>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This is because when your upload is successful, webpack detects a new file and reloads the page.

from https://github.com/facebook/create-react-app/issues/2541#issuecomment-308750412

I don't think we'll do this as it seems like people generally don't use public folder for uploads. And it wouldn't work in production anyway.
I would recommend to use a separate server (which you need anyway) and separate folder for image uploads, and have the app load images from a different host/port (just like it would in production, e.g. from a CDN).

about 4 years ago · Juan Pablo Isaza Report

0

if you are using that function in onsubmit attribute of the form you need to return false from that function

  const handleSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append("poster", document.getElementById('file').files[0]);
    let res = await fetch("http://localhost:5000/api/post/exhibition", {
       method: "POST",
       body: formData
    })
    const json = await res.json()
    console.log(json)
    return false
 }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!