Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of an event in TypeScript in React

I have the following event in onSubmit using React and I am changing it from Javascript to TypeScript.

const submitUserHandler = (e) => {

e.preventDefault();
dispatch(
  authenticate({
    name: e.target.personname.value,
    pw: e.target.password.value,
  })
);
};

I have tried assigning 'e: React.ChangeEvent' to the event, but it prompts an error like this:

Property 'personname' does not exist on type 'EventTarget & HTMLInputElement'.

How could I specify the type also including personname and password? Thanks!

like image 751
David Solsona Avatar asked Dec 02 '25 06:12

David Solsona


1 Answers

You can do something like this

<form
  ref={formRef}
  onSubmit={(e: React.SyntheticEvent) => {
    e.preventDefault();
    const target = e.target as typeof e.target & {
      personname: { value: string };
      password: { value: string };
    };
    const email = target.personname.value; // typechecks!
    const password = target.password.value; // typechecks!
    // etc...
  }}
>
  <div>
    <label>
      Email:
      <input type="personname" name="personname" />
    </label>
  </div>
  <div>
    <label>
      Password:
      <input type="password" name="password" />
    </label>
  </div>
  <div>
    <input type="submit" value="Log in" />
  </div>
</form>

For details, reference

like image 55
DevLoverUmar Avatar answered Dec 03 '25 19:12

DevLoverUmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!