Home > Software design >  Property 'id' does not exist on type 'EventTarget'.ts(2339)
Property 'id' does not exist on type 'EventTarget'.ts(2339)

Time:11-08

I am using React with Typescript.

I am passing id as a prop to my button component. Still getting the mentioned error on e.target.id

  function handleButtonClick(e: React.MouseEvent<HTMLButtonElement>) {
     someOperation(e.target.id)
  }

React: 18.0.0

Typescript: 4.7.4

CodePudding user response:

This should work for your Button Element

  function handleButtonClick(e: React.MouseEvent<HTMLButtonElement>) {
    const target = e.target as HTMLButtonElement;
    someOperation(target.id);
  }

If you want to use properties such as id, name that exist on HTML Elements you can also do.

const target = e.target as Element;

But note to type the exact element if you use properties specific to an element like value for Input

const target = e.target as HTMLInputElement

CodePudding user response:

Replace target with currentTarget

function handleButtonClick(e: React.MouseEvent<HTMLButtonElement>) {
  someOperation(e.currentTarget.id)
}

From the Type definitions for React 18.0:

currentTarget - a reference to the element on which the event listener is registered.

target - a reference to the element from which the event was originally dispatched. This might be a child element to the element on which the event listener is registered.

  • Related