Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i type e.key and e.target.value with typescript in react

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?

like image 782
gpbaculio Avatar asked Nov 23 '25 02:11

gpbaculio


1 Answers

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.

like image 194
maxired Avatar answered Nov 24 '25 20:11

maxired



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!