3

I have the following React code that works ok in JavaScript:

function handleSubmit(event) { event.preventDefault() console.dir(event.target[0].value) console.dir(event.target.usernameInput.value)'EventTarget'. console.dir(event.target.elements.usernameInput.value) } return ( <form onSubmit={handleSubmit}> <label htmlFor="usernameInput">Username:</label> <input id="usernameInput" type="text" onChange={handleChange} /> [...] 

I'd like to do the same with TypeScript but I can't access event.target[0], event.target.elements nor event.target.usernameInput, instead I get "Property '0' does not exist on type 'EventTarget'" and "Property 'usernameInput' does not exist on type 'EventTarget'"

This is the ts code:

const handleSubmit = (event: FormEvent<HTMLFormElement>) => { event.preventDefault() console.dir(event.target[0].value) // Property '0' does not exist on type 'EventTarget'. console.dir(event.target.usernameInput.value) // Property 'usernameInput' does not exist on type 'EventTarget'. console.dir(event.target.elements.usernameInput.value) // Property 'elements' does not exist on type 'EventTarget'. 

How can I access any of those properties?

1 Answer 1

7

If you want to get a reference to the form in TypeScript, use currentTarget instead of target:

const form = event.currentTarget; // do stuff with form // form[0] will be typed as Element, which you can cast to an HTMLInputElement 

But the better way to examine form values in React would be to use controlled components, and on submit, look at the stateful variable that corresponds to the value:

const App = () => { const [username, setUsername] = useState(''); const handleSubmit = () => { console.log(username); }; return ( <form onSubmit={handleSubmit}> <label htmlFor="usernameInput">Username:</label> <input id="usernameInput" value={username} onChange={(e) => { setUsername(e.currentTarget.value); }} /> </form> ); }; 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I'm using the useState approach, just wanted to know the ts equivalent. BTW, event.currentTarget.usernameInput works ok, but event.currentTarget.elements.usernameInput gives me a "Property 'usernameInput' does not exist on type 'HTMLFormControlsCollection'." error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.