When trying to access the dataset on a button after a click, I get this^ error.
linkProvider = (ev: React.SyntheticEvent<EventTarget>) => {
console.debug('ev.target', ev.target.dataset['ix']) // error
}
// in render
providers.map((provider, ix) => (
<button key={provider} data-ix={ix} onClick={this.linkProvider}>{provider}</button>
))
Any ideas how to make it work?
js error "Property 'value' does not exist on type EventTarget" occurs when the type of the event parameter is incorrect. To solve the error, type the event as React. ChangeEvent<HTMLInputElement> . You can then access the value as event.
The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.
The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.
currentTarget is the element. target is the element user clicked on, in the case of click event. It can be the original element or any of its children depending on where user clicks on exactly.
Problem is here Element
, document
, and window
can be an EventTarget
. You should detect your EventTarget
if is an element. So in your case below code should work
linkProvider = (ev: React.SyntheticEvent<EventTarget>) => {
// If event target not an HTMLButtonElement, exit
if (!(ev.target instanceof HTMLButtonElement)) {
return;
}
console.debug('ev.target', ev.target.dataset['ix'])
}
In the short way
linkProvider = (ev: React.SyntheticEvent<HTMLButtonElement>) => {
console.debug('ev.target', ev.currentTarget.dataset['ix'])
}
And also i added example here
Combining both suggestions provided by @Efe and @fatemefazli, I came to a solution that works:
For reference, this is the interface and the reason why it doesn't work with target
: (github link)
interface SyntheticEvent<T> {
/**
* A reference to the element on which the event listener is registered.
*/
currentTarget: EventTarget & T;
// If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
/**
* A reference to the element from which the event was originally dispatched.
* This might be a child element to the element on which the event listener is registered.
*
* @see currentTarget
*/
target: EventTarget;
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With