DGB
DGB

Reputation: 1342

React with TypeScript - Property 'value' does not exist on type 'EventTarget'

I've created a function that fires on button clicks that sets a value to a filter. It works fine however I get the TypeScript error.

Property 'value' does not exist on type 'EventTarget'.

Heres my button function that fires onClick:

  const handleFilterButtonChange = (event: MouseEvent<HTMLButtonElement>) => {
    setTerm(event.target.value);
  };

Upvotes: 0

Views: 728

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370599

The HTMLButtonElement generic indicates the element the listener is attached to, but said element is not necessarily the target. See here for an example:

const handleFilterButtonChange = (event) => {
  console.log(event.target);
};
document.querySelector('div').addEventListener('click', handleFilterButtonChange);
<div>
  <button>click</button>
</div>

Above, the listener is attached to the <div>, but the event.target is the button, since the button was the innermost element clicked.

That's why TypeScript is giving you a warning. Use .currentTarget instead, which will refer to the element the listener is attached to:

const handleFilterButtonChange = (event: MouseEvent<HTMLButtonElement>) => {
    setTerm(event.currentTarget.value);
};

Upvotes: 4

Related Questions