Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'

Viewed 24

On a screen I have, I'm trying to define a function to handle the submit of a form, however, I have a problem with a typescript error:

Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'

My code looks like this:

import React, { FormEvent } from 'react';
import Form from 'react-bootstrap/Form';
import LoadingButton from '../shared/LoadingButton';
import { useSignIn } from '../../hooks/Auth/useSignIn';
import { useHistory } from 'react-router-dom';
import ErrorIndicator from '../shared/ErrorIndicator';

function SignIn() {
    const { mutateAsync, error, isError, isLoading } = useSignIn();
    const history = useHistory();

    const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const data = new FormData(event.target); // Error appears here
        const email = data.get('email')!;
        const password = data.get('password')!;

        await mutateAsync({ email, password });
        history.push('/dashboard');
    };

    return (
        <Form onSubmit={handleSubmit} className='py-3'>
            ...
        </Form>
    );
}

I tried to change the type of the handleSubmit parameter from FormEvent<HTMLFormElement> to FormEvent<EventTarget>, however, that doesn't fix the error.

1 Answers

As commented by both caTS and Konrad Linkowski, it should be event.currentTarget instead of event.target because of event bubbling

Related