5

I am trying to create an onClick event type to capture the target attribute in React while using TypeScript. But I am getting the error "[ts] Property 'getAttribute' does not exist on type 'EventTarget'." Can anyone help provide insight into best practice on how to fix this?

I tried to use another helper function for the event.target part. That way I can typeset this part, and the getAttribute part in this function. However, I was told this is not best practice and wrong approach.

const Option = (props: OptionProps) => {

  const HandleOptionChange = (event: React.MouseEvent<HTMLLIElement>) => {
    return props.onOptionChange(event.target.getAttribute('value'));
  }

  return (
    <li
      key={props.key}
      value={JSON.stringify(props.word)}
      onClick={HandleOptionChange}
    >
      {props.word.value}
    </li>
  )
}

ts error message:

[ts] Property 'getAttribute' does not exist on type 'EventTarget'. any

JS_Minion
  • 51
  • 1
  • 2

3 Answers3

8

this works for me

const HandleOptionChange = (event: React.MouseEvent<HTMLLIElement>) => {
    const el = event.target as HTMLInputElement
    return props.onOptionChange(el.getAttribute('value'));
  }

i've just added HTMLInputElement as event.target type

Davit Yeritsyan
  • 239
  • 1
  • 2
  • 6
  • Why `React.MouseEvent` isn't enough? – Eric Burel Apr 21 '20 at 06:59
  • Typescript doesn't assume that the event target is an element regardless of where the listener resides, see: https://stackoverflow.com/questions/28900077/why-is-event-target-not-element-in-typescript – Mr. Dave Oct 24 '20 at 19:41
  • Note: this is incorrect. See my answer as to why. `target` isn't necessarily the element that your listener is attached to. `target` is the lowest child of the listener that the event is attached to, which you can't guarantee is a specific type of element. In OP's case, since
  • is the lowest child, it will be the same, but JS can't predict the DOM structure. Trying to force-coerce the type is dangerous, and leads to misunderstandings on what the values on the event are. If your
  • contained an , and the user clicked it, the
  • event `target` would return the , not the
  • .
  • – Armel Chesnais Nov 19 '22 at 22:09