Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form.

Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'.

The issue arises when I utilize formData in my code.


const handleSubmit = (e) => {
    e.preventDefault();
    console.log(e.target);
    var data = new FormData(e.target);

Here is how I've structured the rendering:

<form className='signup-form' onSubmit={handleSubmit}>
                            <div className='form-group'>
                                <label>{translations[language]['g29']}*</label>
                                <input
                                    type='text'
                                    className='form-control'
                                    placeholder={translations[language]['g91']}
                                    id='name'
                                    required={true}
                                    name='name'
                                    data-error='Please enter your name'
                                />
                            </div>
                            <div className='form-group'>
                                <label>{translations[language]['g61']}*</label>
                                <input
                                    type='text'
                                    className='form-control'
                                    placeholder={translations[language]['g92']}
                                    id='surname'
                                    required={true}
                                    name='surname'
                                    data-error='Please enter your Surname'
                                />
                            </div>

                            <div className='form-group'>
                                <label>{translations[language]['g24']}*</label>
                                <input
                                    type='email'
                                    className='form-control'
                                    placeholder={translations[language]['g42']}
                                    id='email'
                                    required={true}
                                    name='email'
                                />
                            </div>

                            <div className='form-group'>
                                <label>{translations[language]['g43']}*</label>
                                <input
                                    type='password'
                                    className='form-control'
                                    placeholder={translations[language]['g44']}
                                    id='password'
                                    required={true}
                                    name='password'
                                />
                            </div>
                            <div className='form-group'>
                                <label>{translations[language]['g43']}*</label>
                                <input
                                    type='password'
                                    className='form-control'
                                    placeholder={translations[language]['g93']}
                                    id='passwordControl'
                                    required={true}
                                    name='passwordControl'
                                />
                            </div>
                            <div className='form-group'>
                                <label>{translations[language]['g94']}</label>
                                <div style={{ display: 'flex' }}>
                                    <div style={{ marginRight: '8px', display: 'flex', alignItems: 'center' }}>
                                        <input
                                            type='radio'
                                            style={{ marginRight: 6 }}
                                            //className={styles.check_input}
                                            name='gender'
                                            id="female"
                                            required={true}
                                        />
                                        <div>{translations[language]['g95']}</div>
                                    </div>

                                    <div style={{ marginRight: '8px', display: 'flex', alignItems: 'center' }}>
                                        <input
                                            type='radio'
                                            style={{ marginRight: 6 }}
                                            // value={!gender}
                                            //className={styles.check_input}
                                            name='gender'
                                            id="male"
                                            required={true}
                                        />
                                        <div>{translations[language]['g96']}</div>
                                    </div>
                                    <div style={{ display: 'flex', alignItems: 'center' }}>
                                        <input
                                            type='radio'
                                            style={{ marginRight: 6 }}
                                            // value={!gender}
                                            //className={styles.check_input}
                                            name='gender'
                                            id="other"
                                            required={true}
                                        />
                                        <div>{translations[language]['g97']}</div>
                                    </div>
                                </div>
                            </div>
                           
         
              <button onClick={handleSubmit} type='submit' className='btn btn-primary'>
                {translations[language]['g53']}
              </button>
              <Link href='/'>
                <a className='return-store'>{translations[language]['g51']}</a>
              </Link>
            </form>

Upon clicking the sign-up button, I encounter an error that I'm unable to troubleshoot.

Answer №1

When encountering the error message, it specifies that the parameter must be an instance of HTMLFormElement. In React, a convenient way to obtain the form instance is by utilizing useRef.

import{ useRef } from 'react';

const Form = () => {
  const formRef = useRef(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const form = formRef.current;
    if(!form) return false;
    const formData = new FormData(form); 
    console.log(formData);
  }

  return (
    <form ref={formRef} onSubmit={handleSubmit}>
      <input type="text" name="name" />
      <button type="submit">Submit</button>
    </form>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Allowing users to easily copy and paste within expansion panels

Currently, I am exploring the possibilities of utilizing the ExpansionPanel component provided by Material-UI. However, I am encountering a challenge in enabling text selection on the ExpansionPanelSummary component to allow users to Copy and Paste text ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

Using typescript in react to define conditional prop types

Currently, I am utilizing react-select as my select component with the multi prop. However, my goal is to have the onChange argument set as an array of options when the multi prop is true, and as OptionType when false. To achieve this, I am implementing di ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

Exploring the capabilities of Google Drive API using Requests library

I am interested in streaming a file from a remote source to Google Drive. By utilizing the request library, you can easily download files locally like so: request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png') ...

Dynamic routing in Next.js expands upon the current path

With my Next.js blog utilizing Strapi CMS, I am attempting to arrange the posts by their respective categories. I have set up a dynamic route for categories [id].js and have implemented getStaticPaths as shown below: export async function getStaticPaths() ...

How can an Embedded React + JSS component safeguard generic elements such as <button> and <p> from being affected by the page's style?

I am facing a challenge with a React component that is being embedded in various webpages, either through an extension or as a third-party tool. Most of the styling for this component is done using JSS, ensuring unique class names that cannot be overridde ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

Eliminate item upon alteration of redux state

I am facing an issue with updating a component when removing an element from the Redux state. Here is my component: const mapStateToProps = state => ({ products: state.shoppingBasket.list, }); const ShoppingBasket = React.createClass({ propTypes: ...

The database server is not appearing on the main.js page of the client

My client's main.js file contains code that is meant to display previous form entries on the webpage, but after submitting the form, no entries appear on the HTML page. My server is running on port 7777 and the root route works in Postman, as does the ...

angular.js watch() method is not functioning properly during a JSON call

I am trying to trigger a method whenever the value of my $http.selectedSong (model value) changes, but for some reason it is not working. Any ideas on why this could be happening?: app.controller('songController', ['$http', function($h ...

Unable to rectify the installed npm module issue

I removed the @toast-ui/react-image-editor package from my react app's server side thinking it needed to be on the client side. After installing it on the client side and restarting the app, it could not be found. Here is a basic overview of my folde ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...