Error TS7053 when accessing any index of the target of a React.FormEvent

Basically I’m following this tutorial, converting it to React and TypeScript

Here’s the code I’ve written for the onSubmit event

const signUp = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();

  // Problematic lines of code
  const email = event.target[0].value;
  const password = event.target[1].value;
};

And the basic signup form

  return (
    <div>
      <form id="signUp" onSubmit={signUp}>
        <h3>Sign up</h3>
        <label>Email </label>
        <input type="email" name="email" />
        <label>Password </label>
        <input type="password" name="password" />
        <br></br>
        <input type="submit"></input>
      </form>
    </div>
  )

The full error:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'.
  Property '0' does not exist on type 'EventTarget'.  TS7053

Answer

You seem to be getting it incorrectly. onSubmit event will not contain any input values. To access the input values, I’d suggest you store them in a state and bind it using onChange so that when the form is submitted you can validate using the state values.

Short answer to get this working:

Add an id attribute to the input tags to access the values on submit.

<input type="email" name="email" id="email" />
<input type="password" name="password" id="password" />


const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

Example: https://codesandbox.io/s/form-submit-demo-fjls0