3
votes

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

1

1 Answers

5
votes

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