Issue
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?
Solution
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>
);
};
Answered By - CertainPerformance
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.