0

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);
  };

1 Answer 1

4

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);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.