Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript get Data Attribute From Click Event

So I have a React component with a button which has a click handler which uses the data-* attribute. If this was straight React then I know how to get the value from the data-* attribute. However I am learning how to use TypeScript so I have no idea how to get access to this attribute. So what is the best way to get access to the data-* attribute using TypeScript?

This is my JSX code for the button:

<button type="button" className="NavLink" data-appMode={ AppMode.MAIN } onClick={ this.handleAppModeClick.bind(this) }>Main</button>

This is my handler for the click event:

handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
    // What code should go here to access the data-appMode attribute?
}
like image 411
Scott Kingdon Avatar asked Oct 30 '19 21:10

Scott Kingdon


2 Answers

You most likely will have to use as syntax , depending which property you want to access on e.target.

handleAppModeClick(e: React.MouseEvent) {
    const appMode = (e.target as HTMLButtonElement).getAttribute('data-appMode');
}
like image 87
givehug Avatar answered Oct 17 '22 21:10

givehug


Use e.currentTarget and then use HTML standard method getAttribute. No coercion necessary.

const appMode = e.currentTarget.getAttribute('data-appmode');

(note lowercase in the attribute name to avoid warnings from react)

currentTarget is already correctly typed.

If you read the definitions of React's event types you can see that MouseEvent extends SyntheticEvent, which extends BaseSyntheticEvent, which includes the property target and currentTarget, among others. The HTMLElement type you provide gets applied to currentTarget, so you have access to all the right stuff. If you use target you'll get a compile error about getAttribute not being valid for type EventTarget.

What's the difference?

The currentTarget is the element where you're putting your handler, onClick. The target is where the event originally came from (more here). This is not necessarily the same because events bubble up. See the PR referenced in the type definitions file for a complete discussion on why they're typed differently.

like image 27
Chris Avatar answered Oct 17 '22 22:10

Chris