React FormEvent<HTMLFormElement> form input props types

Viewed 5364

How to make types for form inputs?

const Index = () => {
  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    console.log(e.currentTarget.elements.email)
  }

  return (
    <Layout>
      <form onSubmit={handleSubmit}>
        <input name='email' type='email' autoComplete='email' required />
        <input name='password' type='password' autoComplete='password' required />
        <button type='submit'>Login</button>
      </form>
    </Layout>
  )
}

Type error:

Property 'email' does not exist on type 'HTMLFormControlsCollection'.

2 Answers

Here FormEvent<HTMLFormElement> will give an array list as HTMLFormControlsCollection .

So when you are trying to get the email like this e.currentTarget.elements.email it throws the error as,

Property 'email' does not exist on type 'HTMLFormControlsCollection'.

So to get the value of email, You need to get the email element inside an array as

e.currentTarget.elements[0] (as email is first element)

So now we got the email input element and hence let as assign as HTMLInputElement.. and to get the value use,

console.log((e.currentTarget.elements[0] as HTMLInputElement).value);

Working example:

https://codesandbox.io/s/react-with-typescript01-37jc4

Update:

As mentioned in the comments section, I have made this update where you could also use,

console.log((e.currentTarget.elements.namedItem('email') as HTMLInputElement).value);

to get the email value.. But here to get the email value from the array collection I have described with [0] ..

Updated Codesandbox

https://codesandbox.io/s/react-with-typescript01-26www

Related