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?
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