Home > OS >  React TypeScript Submit Form Through Input Field onChange
React TypeScript Submit Form Through Input Field onChange

Time:08-20

I have little experience with TypeScript and I'm trying to submit a form, not only from the submit button, but also from the field OnChange event and together with another handler that is working fine already.

Here's A summary of what I got so far:

import React from 'react';

function App() {
    const onSomeOtherHandler = (event: ChangeEvent<HTMLInputElement>) => {
        // my logic
    };

    const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        // my logic
    };

    return(
        <form onSubmit={handleFormSubmit}>
            <input onChange={(e) => {
                    onSomeOtherHandler(e);
                    handleFormSubmit(e);
              }
            } />
            <button type=”submit”>
                Calculate
            </button>
        </form>
    );
}

export default App;

When I set handleFormSubmit(e) the way I did, it returns me an error:

Argument of type 'ChangeEvent<HTMLInputElement>' is not assignable to parameter of type 'FormEvent<HTMLFormElement>'.
  Types of property 'currentTarget' are incompatible.
    Type 'EventTarget & HTMLInputElement' is not assignable to type 'EventTarget & HTMLFormElement'.
      Type 'EventTarget & HTMLInputElement' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, elements, encoding, and 8 more.]

How do I pass the right form event through that field onChange? Or should I do it in some other way that I´m not aware of? Or should I trigger the submit button?

CodePudding user response:

use this type because you have tow way to submit with enter and click.
e: React.FormEvent<EventTarget || HTMLFormElement>)

  • Related