Reputation: 31949
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?
Upvotes: 33
Views: 28332
Reputation: 31949
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;
// ...
}
Upvotes: 4
Reputation: 486
If I may try to add to Efe's response:
I think it makes sense also to check that the property dataset
has the ix
attribute before you use the attribute*:
linkProvider = (ev: React.SyntheticEvent<EventTarget>) => {
if (!(ev.target instanceof HTMLButtonElement)) {
return;
}
if (ev.target.dataset.ix) {
/// event handler logic
}
}
*got that example from a front-end-masters course
Upvotes: 0
Reputation: 5796
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
Upvotes: 55