Event.target types for name input in FromHandler with TypeScript

Viewed 16

I have a simple form in a React SPA with typescript.

I'm going to make this form processing simple, without adding component state and so, just to get value from the named input, name = 'gameId'.

There are two ways I've tried in the example below:

  1. If I use event.target, TS says the "children" doesn't exist on type 'EventTarget'
  2. If I use event.currentTarget, TS says the "gameId" doesn't exist on type 'HTMLCollection'.

Is there any way to solve these?

const submitAcceptGameHandler: React.FormEventHandler<HTMLFormElement> = async (event) => {
  event.preventDefault();
  
  // 1st
  // Property 'children' does not exist on type 'EventTarget'.ts(2339)
  const inputData = event.target.children.gameId.value;

  // 2nd
  // Property 'gameId' does not exist on type 'HTMLCollection'.ts(2339)
  const inputData = event.currentTarget.children.gameId.value;
  
    console.log(inputData);
  };
<form onSubmit={submitAcceptGameHandler}>
  <button type="submit">ACCEPT GAME</button>
  <input name="gameId" type="text" placeholder={'Input game id...'}></input>
</form>
1 Answers

The issue with the event.target.children

children is an HTMLCollection, similar to an array. You can get values by its index children[0] or chilren[1]

Either you need to go over all your children or convert it to an array and find the desired component by its name or id

To convert you can just use the spread operator

const children = [...event.target.children]
const gameId = children.find(child => child.name === "gameId")?.value

ANYWAY

I would highly recommend having control over your fields and always having state management for them. You can even use some libraries to manage your forms.

I prefer using react-hook-form, but you can choose anything you want

Related