3

i need e.key and e.target.value but i can't seem to make it work with this code:

const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement> ) => {
  if(e.key ==='Enter') { 
    dfTextQuery(e.target.value)
  }
};

why is target not having the value property? and i am getting an error:

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

i was expecting with HTMLInputElement, it should work. how do i type e.key and e.target.value with typescript in react?

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

1 Answers1

3

In the browser, events are bubbling, going from child to parent. the target element from your event is the source of the original event. In your case, the keyboard event will be dispatched from your input field, and will never come from another child.

Instead of using target, you can use currentTarget which corresponds to the DOM element on which the listener is attached. This will be your input field, and so will always be an HTMLInputElement.

maxired
  • 51
  • 3